Commit Graph

1859 Commits

Author SHA1 Message Date
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
Michael Goulet
e4be97cfe7 Try not to make obligations in handle_opaque_type 2024-06-11 14:10:11 -04:00
Michael Goulet
4efb13b0c2 Rename some things 2024-06-11 13:52:51 -04:00
Michael Goulet
44a6f72a72 Make ObligationEmittingRelation deal with Goals only 2024-06-11 13:52:51 -04:00
Michael Goulet
4038010436 Get rid of PredicateObligations 2024-06-11 13:52:51 -04:00
Gurinder Singh
e47ea38da8 Make suggestion to change Fn to FnMut work with methods well 2024-06-10 16:28:05 +05:30
Michael Goulet
91274c84b9 Uplift TypeRelation and Relate 2024-06-06 07:50:19 -04:00
Boxy
60a5bebbe5 Add Ty to mir::Const::Ty 2024-06-05 22:25:41 +01:00
Boxy
58feec9b85 Basic removal of Ty from places (boring) 2024-06-05 22:25:38 +01:00
Amanda Stjerna
7b5b7a7010 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](85f90a4612/compiler/rustc_borrowck/src/type_check/liveness/trace.rs (L219)) should be inspected by a reviewer,
in particular the one on L#259 in this PR, which should be trivial
for someone with the right background knowledge.

I also included some minor lints I found on the way there that I
couldn't help myself from addressing.
2024-06-05 10:57:27 +02:00
Michael Goulet
5019bb608a
Rollup merge of #125667 - oli-obk:taintify, r=TaKO8Ki
Silence follow-up errors directly based on error types and regions

During type_of, we used to just return an error type if there were any errors encountered. This is problematic, because it means a struct declared as `struct Foo<'static>` will end up not finding any inherent or trait impls because those impl blocks' `Self` type will be `{type error}` instead of `Foo<'re_error>`. Now it's the latter, silencing nonsensical follow-up errors about `Foo` not having any methods.

Unfortunately that now allows for new follow-up errors, because borrowck treats `'re_error` as `'static`, causing nonsensical errors about non-error lifetimes not outliving `'static`. So what I also did was to just strip all outlives bounds that borrowck found, thus never letting it check them. There are probably more nuanced ways to do this, but I worried there would be other nonsensical errors if some outlives bounds were missing. Also from the test changes, it looked like an improvement everywhere.
2024-06-04 08:52:12 -04:00
Michael Goulet
a41c44f21c Nits and formatting 2024-06-03 10:02:08 -04:00
Michael Goulet
1e72c7f536 Add cycle errors to ScrubbedTraitError to remove a couple more calls to new_with_diagnostics 2024-06-03 09:27:52 -04:00
Michael Goulet
27f5eccd1f Move FulfillmentErrorCode to rustc_trait_selection too 2024-06-03 09:27:52 -04:00
Michael Goulet
94a524ed11 Use ScrubbedTraitError in more places 2024-06-03 09:27:52 -04:00
Michael Goulet
eb0a70a557 Opt-in diagnostics reporting to avoid doing extra work in the new solver 2024-06-03 09:27:52 -04:00
Michael Goulet
54b2b7d460 Make TraitEngines generic over error 2024-06-03 09:27:52 -04:00
bors
1d52972dd8 Auto merge of #125778 - estebank:issue-67100, r=compiler-errors
Use parenthetical notation for `Fn` traits

Always use the `Fn(T) -> R` format when printing closure traits instead of `Fn<(T,), Output = R>`.

Address #67100:

```
error[E0277]: expected a `Fn()` closure, found `F`
 --> file.rs:6:13
  |
6 |     call_fn(f)
  |     ------- ^ expected an `Fn()` closure, found `F`
  |     |
  |     required by a bound introduced by this call
  |
  = note: wrap the `F` in a closure with no arguments: `|| { /* code */ }`
note: required by a bound in `call_fn`
 --> file.rs:1:15
  |
1 | fn call_fn<F: Fn() -> ()>(f: &F) {
  |               ^^^^^^^^^^ required by this bound in `call_fn`
help: consider further restricting this bound
  |
5 | fn call_any<F: std::any::Any + Fn()>(f: &F) {
  |                              ++++++
```
2024-06-03 08:14:03 +00:00
Michael Goulet
333458c2cb Uplift TypeRelation and Relate 2024-06-01 12:50:58 -04:00
Matthias Krüger
4b41136a47
Rollup merge of #125652 - amandasystems:you-dropped-something, r=oli-obk
Revert propagation of drop-live information from Polonius

#64749 introduced a flow of drop-use data from Polonius to `LivenessResults::add_extra_drop_facts()`, which makes `LivenessResults` agree with Polonius on liveness in the presence of free regions that may be dropped. Later changes accidentally removed this flow. This PR restores it.
2024-05-31 17:05:23 +02:00
Matthias Krüger
379233242b
Rollup merge of #125635 - fmease:mv-type-binding-assoc-item-constraint, r=compiler-errors
Rename HIR `TypeBinding` to `AssocItemConstraint` and related cleanup

Rename `hir::TypeBinding` and `ast::AssocConstraint` to `AssocItemConstraint` and update all items and locals using the old terminology.

Motivation: The terminology *type binding* is extremely outdated. "Type bindings" not only include constraints on associated *types* but also on associated *constants* (feature `associated_const_equality`) and on RPITITs of associated *functions* (feature `return_type_notation`). Hence the word *item* in the new name. Furthermore, the word *binding* commonly refers to a mapping from a binder/identifier to a "value" for some definition of "value". Its use in "type binding" made sense when equality constraints (e.g., `AssocTy = Ty`) were the only kind of associated item constraint. Nowadays however, we also have *associated type bounds* (e.g., `AssocTy: Bound`) for which the term *binding* doesn't make sense.

---

Old terminology (HIR, rustdoc):

```
`TypeBinding`: (associated) type binding
├── `Constraint`: associated type bound
└── `Equality`: (associated) equality constraint (?)
    ├── `Ty`: (associated) type binding
    └── `Const`: associated const equality (constraint)
```

Old terminology (AST, abbrev.):

```
`AssocConstraint`
├── `Bound`
└── `Equality`
    ├── `Ty`
    └── `Const`
```

New terminology (AST, HIR, rustdoc):

```
`AssocItemConstraint`: associated item constraint
├── `Bound`: associated type bound
└── `Equality`: associated item equality constraint OR associated item binding (for short)
    ├── `Ty`: associated type equality constraint OR associated type binding (for short)
    └── `Const`: associated const equality constraint OR associated const binding (for short)
```

r? compiler-errors
2024-05-31 08:50:22 +02:00
León Orell Valerian Liehr
34c56c45cf
Rename HIR TypeBinding to AssocItemConstraint and related cleanup 2024-05-30 22:52:33 +02:00
Esteban Küber
e6bd6c2044 Use parenthetical notation for Fn traits
Always use the `Fn(T) -> R` format when printing closure traits instead of `Fn<(T,), Output = R>`.

Fix #67100:

```
error[E0277]: expected a `Fn()` closure, found `F`
 --> file.rs:6:13
  |
6 |     call_fn(f)
  |     ------- ^ expected an `Fn()` closure, found `F`
  |     |
  |     required by a bound introduced by this call
  |
  = note: wrap the `F` in a closure with no arguments: `|| { /* code */ }`
note: required by a bound in `call_fn`
 --> file.rs:1:15
  |
1 | fn call_fn<F: Fn() -> ()>(f: &F) {
  |               ^^^^^^^^^^ required by this bound in `call_fn`
help: consider further restricting this bound
  |
5 | fn call_any<F: std::any::Any + Fn()>(f: &F) {
  |                              ++++++
```
2024-05-29 22:26:54 +00:00
Oli Scherer
a34c26e7ec Make body_owned_by return the body directly.
Almost all callers want this anyway, and now we can use it to also return fed bodies
2024-05-29 10:04:08 +00:00
Oli Scherer
39b39da40b Stop proving outlives constraints on regions we already reported errors on 2024-05-29 09:27:07 +00:00
Amanda Stjerna
8066ebc294 Move the rest of the logic into add_extra_drop_facts() 2024-05-28 16:02:09 +02:00
Amanda Stjerna
e15564672e Make drop-use fact collection simpler for polonius
This shunts all the complexity of siphoning off the drop-use facts
into `LivenessResults::add_extra_drop_facts()`, which may or may
not be a good approach.
2024-05-28 15:49:22 +02:00
Amanda Stjerna
077a8219b0 Fix back-porting drop-livess from Polonius to tracing 2024-05-28 13:05:56 +02:00
Boxy
fe2d7794ca Remove DefId from EarlyParamRegion (tedium/diagnostics) 2024-05-24 18:06:53 +01:00
Michael Goulet
1c8230ea3c Uplift OutlivesPredicate, remove a bunch of unnecessary associated types from Interner 2024-05-21 17:00:45 -04:00
bors
e875391458 Auto merge of #123812 - compiler-errors:additional-fixes, r=fmease
Follow-up fixes to `report_return_mismatched_types`

Some renames, simplifications, fixes, etc. Follow-ups to #123804. I don't think it totally disentangles this code, but it does remove some of the worst offenders on the "I am so confused" scale (e.g. `get_node_fn_decl`).
2024-05-21 08:06:41 +00:00
bors
9cb6bb8599 Auto merge of #125284 - compiler-errors:uplift-misc, r=lcnr
Uplift `RegionVid`, `TermKind` to `rustc_type_ir`, and `EagerResolver` to `rustc_next_trait_solver`

- Uplift `RegionVid`. This was complicated due to the fact that we implement `polonius_engine::Atom` for `RegionVid` -- but I just separated that into `PoloniusRegionVid`, and added `From`/`Into` impls so it can be defined in `rustc_borrowck` separately. Coherence 😵
- Change `InferCtxtLike` to expose `opportunistically_resolve_{ty,ct,lt,int,float}_var` so that we can uplift `EagerResolver` for use in the canonicalization methods.
- Uplift `TermKind` much like `GenericArgKind`

All of this is miscellaneous dependencies for making more `EvalCtxt` methods generic.
2024-05-21 02:51:38 +00:00
Michael Goulet
b826eb219c Rename confusing function name 2024-05-20 19:56:48 -04:00
Michael Goulet
569fb43aa0 Uplift RegionVid 2024-05-20 13:57:58 -04:00
Matthias Krüger
9987e900c0
Rollup merge of #125173 - scottmcm:never-checked, r=davidtwco
Remove `Rvalue::CheckedBinaryOp`

Zulip conversation: <https://rust-lang.zulipchat.com/#narrow/stream/189540-t-compiler.2Fwg-mir-opt/topic/intrinsics.20vs.20binop.2Funop/near/438729996>
cc `@RalfJung`

While it's a draft,
r? ghost
2024-05-20 18:13:48 +02:00
Joshua Wong
5d7eda224e fix suggestion in E0373 for !Unpin coroutines
Coroutines can be prefixed with the `static` keyword to make them
`!Unpin`.
However, given the following function:

```rust

fn check() -> impl Sized {
    let x = 0;
    #[coroutine]
    static || {
        yield;
        x
    }
}
```

We currently suggest prefixing `move` before `static`, which is
syntactically incorrect:

```
error[E0373]: coroutine may outlive the current function, but it borrows
...
 --> src/main.rs:6:5
  |
6 |     static || {
  |     ^^^^^^^^^ may outlive borrowed value `x`
7 |         yield;
8 |         x
  |         - `x` is borrowed here
  |
note: coroutine is returned here
 --> src/main.rs:6:5
  |
6 | /     static || {
7 | |         yield;
8 | |         x
9 | |     }
  | |_____^
help: to force the coroutine to take ownership of `x` (and any other
referenced variables), use the `move` keyword
  |     // this is syntactically incorrect, it should be `static move ||`
6 |     move static || {
  |     ++++

```

This PR suggests adding `move` after `static` for these coroutines.
2024-05-19 19:13:52 -05:00
Matthias Krüger
d5bef41ee5
Rollup merge of #124948 - blyxyas:remove-repeated-words, r=compiler-errors
chore: Remove repeated words (extension of #124924)

When I saw #124924 I thought "Hey, I'm sure that there are far more than just two typos of this nature in the codebase". So here's some more typo-fixing.

Some found with regex, some found with a spellchecker. Every single one manually reviewed by me (along with hundreds of false negatives by the tools)
2024-05-19 22:50:55 +02:00
bors
eb1a5c9bb3 Auto merge of #125077 - spastorino:add-new-fnsafety-enum2, r=jackh726
Rename Unsafe to Safety

Alternative to #124455, which is to just have one Safety enum to use everywhere, this opens the posibility of adding `ast::Safety::Safe` that's useful for unsafe extern blocks.

This leaves us today with:

```rust
enum ast::Safety {
    Unsafe(Span),
    Default,
    // Safe (going to be added for unsafe extern blocks)
}

enum hir::Safety {
    Unsafe,
    Safe,
}
```

We would convert from `ast::Safety::Default` into the right Safety level according the context.
2024-05-18 19:35:24 +00:00
blyxyas
c5c820e7fb Fix typos (taking into account review comments) 2024-05-18 18:12:18 +02:00
Scott McMurray
95c0e5c6a8 Remove Rvalue::CheckedBinaryOp 2024-05-17 20:33:02 -07:00
Santiago Pastorino
6b46a919e1
Rename Unsafe to Safety 2024-05-17 18:33:37 -03:00
Michael Goulet
138881b315 Uplift Goal to rustc_type_ir 2024-05-16 14:24:22 -04:00
Michael Goulet
412dc28d6a Make P parameter explicit 2024-05-16 14:23:47 -04:00
Michael Goulet
11ec3eca74 Rename ToPredicate for Upcast 2024-05-16 14:23:47 -04:00
Michael Goulet
3bcdf3058e split out AliasTy -> AliasTerm 2024-05-13 11:59:42 -04:00
Michael Goulet
e444017b49 Consolidate obligation cause codes for where clauses 2024-05-11 02:10:45 -04:00
bors
19dacee0d8 Auto merge of #124982 - compiler-errors:uplift-trait-ref, r=lcnr
Uplift `TraitRef` into `rustc_type_ir`

Emotional rollercoaster

r? lcnr
2024-05-10 22:24:53 +00:00
Michael Goulet
1e5ec0a12c Lift TraitRef into rustc_type_ir 2024-05-10 15:44:03 -04:00
bors
2cce088584 Auto merge of #124952 - compiler-errors:no-error, r=lcnr
Rename some `FulfillmentErrorCode`/`ObligationCauseCode` variants to be less redundant

1. Rename some `FulfillmentErrorCode` variants.
2. Always use `ObligationCauseCode::` to prefix a code, rather than using a glob import and naming them through `traits::`.
3. Rename some `ObligationCauseCode` variants -- I wasn't particularly thorough with thinking of a new names for these, so could workshop them if necessary.
4. Misc stuff from renaming.

r? lcnr
2024-05-10 18:11:02 +00:00
Michael Goulet
6f77bfe8b6 Name tweaks 2024-05-10 10:42:57 -04:00
Michael Goulet
9108294a6c More rename fallout 2024-05-10 10:42:57 -04:00
Michael Goulet
534e267d48 Rename some ObligationCauseCode variants 2024-05-10 10:42:57 -04:00
Michael Goulet
04c049498d rename some variants in FulfillmentErrorCode 2024-05-10 10:42:14 -04:00
Matthias Krüger
9a9ec90567
Rollup merge of #124957 - compiler-errors:builtin-deref, r=michaelwoerister
Make `Ty::builtin_deref` just return a `Ty`

Nowhere in the compiler are we using the mutability part of the `TyAndMut` that we used to return.
2024-05-10 16:10:47 +02:00
bors
f7b1501ce7 Auto merge of #124961 - matthiaskrgr:rollup-1jj65p6, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #124551 (Add benchmarks for `impl Debug for str`)
 - #124915 (`rustc_target` cleanups)
 - #124918 (Eliminate some `FIXME(lcnr)` comments)
 - #124927 (opt-dist: use xz2 instead of xz crate)
 - #124936 (analyse visitor: build proof tree in probe)
 - #124943 (always use `GenericArgsRef`)
 - #124955 (Use fewer origins when creating type variables.)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-10 06:50:46 +00:00
Matthias Krüger
0ee258009c
Rollup merge of #124955 - nnethercote:next_ty_var, r=lcnr
Use fewer origins when creating type variables.

To reduce lots of repetitive boilerplate code. Details in the individual commit messages.

r? ``@lcnr``
2024-05-10 07:30:22 +02:00
Matthias Krüger
7e4f6082ce
Rollup merge of #124918 - nnethercote:FIXME-lcnr, r=lcnr
Eliminate some `FIXME(lcnr)` comments

In some cases this involved changing code. In some cases the comment was able to removed or replaced.

r? ``@lcnr``
2024-05-10 07:30:20 +02:00
bors
98dabb622a Auto merge of #124953 - compiler-errors:own-params, r=lcnr
Rename `Generics::params` to `Generics::own_params`

I hope this makes it slightly more obvious that `generics.own_params` is insufficient when considering nested items. I didn't actually audit any of the usages, for the record.

r? lcnr
2024-05-10 04:43:57 +00:00
Michael Goulet
d50c2b0a52 Make builtin_deref just return a Ty 2024-05-09 22:55:00 -04:00
Michael Goulet
1c19b6ad60 Rename Generics::params to Generics::own_params 2024-05-09 20:58:46 -04:00
Nicholas Nethercote
fe843feaab Use fewer origins when creating type variables.
`InferCtxt::next_{ty,const}_var*` all take an origin, but the
`param_def_id` is almost always `None`. This commit changes them to just
take a `Span` and build the origin within the method, and adds new
methods for the rare cases where `param_def_id` might not be `None`.
This avoids a lot of tedious origin building.

Specifically:
- next_ty_var{,_id_in_universe,_in_universe}: now take `Span` instead of
  `TypeVariableOrigin`
- next_ty_var_with_origin: added

- next_const_var{,_in_universe}: takes Span instead of ConstVariableOrigin
- next_const_var_with_origin: added

- next_region_var, next_region_var_in_universe: these are unchanged,
  still take RegionVariableOrigin

The API inconsistency (ty/const vs region) seems worth it for the
large conciseness improvements.
2024-05-10 09:47:46 +10:00
Esteban Küber
2df4f7dd8c 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-05-09 23:25:31 +00:00
Matthias Krüger
a40fa8f443
Rollup merge of #124924 - goofylfg:master, r=est31
chore: remove repetitive words
2024-05-09 19:09:31 +02:00
Matthias Krüger
ebeedf05cb
Rollup merge of #124893 - xldenis:public-region-apis, r=lcnr
Make a minimal amount of region APIs public

Tools like Creusot, Prusti or Gillian-Rust need to access information about the loans and regions that exist in MIR programs. While `rustc` provides information about loans, there is currently no public way to reason about the regions present in a MIR program. In particular, we to know which regions are actually equal to each other and which ones outlive each other. Currently, `rustc` provides access to `RegionInferenceContext` but the public api hides that last portion of the information.

This PR proposes to make a few apis public, allowing verifiers to reason about the lifetimes present in Rust programs:
- [eval_equal](https://doc.rust-lang.org/beta/nightly-rustc/rustc_borrowck/region_infer/struct.RegionInferenceContext.html#method.eval_equal)
- [eval_outlives](https://doc.rust-lang.org/beta/nightly-rustc/rustc_borrowck/region_infer/struct.RegionInferenceContext.html#method.eval_outlives)
- (Optional) [constraint_sccs](https://doc.rust-lang.org/beta/nightly-rustc/rustc_borrowck/region_infer/struct.RegionInferenceContext.html#method.constraint_sccs)

The first two functions would allow us to compare regions and from this we can construct the set of `RegionVid` which are actually equal to each other, and then recover the inclusions between those regions, while the second allows for more direct, but _low level_ access to that information.
2024-05-09 19:09:29 +02:00
goofylfg
5120010b02 chore: remove repetitive words 2024-05-09 12:41:48 +00:00
Nicholas Nethercote
609b9a67c9 Correct a comment.
I tried simplifying `RegionCtxt`, which led me to finding that the
fields are printed in `sccs_info`.
2024-05-09 20:15:42 +10:00
bors
37dc766378 Auto merge of #124831 - nnethercote:rustc_data_structures-cleanups, r=michaelwoerister
`rustc_data_structures` cleanups

Some improvements I found while looking through this code.

r? `@michaelwoerister`
2024-05-09 04:04:09 +00:00
Nicholas Nethercote
d3d01e1cd3 Remove vec_linked_list.
It provides a way to effectively embed a linked list within an
`IndexVec` and also iterate over that list. It's written in a very
generic way, involving two traits `Links` and `LinkElem`. But the
`Links` trait is only impl'd for `IndexVec` and `&IndexVec`, and the
whole thing is only used in one module within `rustc_borrowck`. So I
think it's over-engineered and hard to read. Plus it has no comments.

This commit removes it, and adds a (non-generic) local iterator for the
use within `rustc_borrowck`. Much simpler.
2024-05-09 08:13:24 +10:00
Xavier Denis
d4c6c772c3 Make a minimal amount of region APIs public 2024-05-08 19:22:04 +02:00
lcnr
24ee32cf70 borrowck: more eagerly prepopulate opaques 2024-05-06 16:04:57 +00:00
lcnr
5f044f3528 BorrowckInferCtxt: infcx by value 2024-05-06 15:20:13 +00:00
Mark Rousskov
a64f941611 Step bootstrap cfgs 2024-05-01 22:19:11 -04:00
Matthias Krüger
784316eadc
Rollup merge of #124511 - nnethercote:rm-extern-crates, r=fee1-dead
Remove many `#[macro_use] extern crate foo` items

This requires the addition of more `use` items, which often make the code more verbose. But they also make the code easier to read, because `#[macro_use]` obscures where macros are defined.

r? `@fee1-dead`
2024-04-30 15:04:08 +02:00
Matthias Krüger
6ce9708ce5
Rollup merge of #124185 - beepster4096:move_data_base_local_infallible, r=pnkfelix
Remove optionality from MoveData::base_local

This is an artifact from when Places could be based on statics and not just locals. Now, all move paths either are locals or have parents, so this doesn't need to return Option anymore.
2024-04-29 22:37:50 +02:00
Nicholas Nethercote
99e036bd21 Remove extern crate rustc_middle from numerous crates. 2024-04-29 14:50:45 +10:00
Esteban Küber
64a4cdcfd4 review comment: rename method 2024-04-25 18:26:36 +00:00
Esteban Küber
abdb64d4ea Check equivalence of indices in more cases 2024-04-25 16:55:33 +00:00
Esteban Küber
ad6ae61246 Don't suggest split_at_mut when the multiple borrows have the same index 2024-04-25 16:55:33 +00:00
Esteban Küber
9f9f0aa534 Mention split_at_mut when mixing mutability in indexing ops
Emit suggestion when encountering

```rust
let a = &mut foo[0];
let b = &foo[1];
a.use_mut();
```
2024-04-25 16:55:33 +00:00
Esteban Küber
dbaa4e2148 Only suggest split_at_mut on indexing borrowck errors for std types 2024-04-25 16:55:32 +00:00
Esteban Küber
386236f289 Detect borrow error involving sub-slices and suggest split_at_mut
```
error[E0499]: cannot borrow `foo` as mutable more than once at a time
  --> $DIR/suggest-split-at-mut.rs:13:18
   |
LL |     let a = &mut foo[..2];
   |                  --- first mutable borrow occurs here
LL |     let b = &mut foo[2..];
   |                  ^^^ second mutable borrow occurs here
LL |     a[0] = 5;
   |     ---- first borrow later used here
   |
   = help: use `.split_at_mut(position)` or similar method to obtain two mutable non-overlapping sub-slices
```

Address most of #58792.

For follow up work, we should emit a structured suggestion for cases where we can identify the exact `let (a, b) = foo.split_at_mut(2);` call that is needed.
2024-04-25 16:55:32 +00:00
bors
31e6e8c6c5 Auto merge of #119650 - chenyukang:yukang-fix-118596-ref-mut, r=wesleywiser
Suggest ref mut for pattern matching assignment

Fixes #118596
2024-04-25 08:52:19 +00:00
Esteban Küber
ad9a5a5f9f Suggest cloning captured binding in move closure
```
error[E0507]: cannot move out of `bar`, a captured variable in an `FnMut` closure
  --> $DIR/borrowck-move-by-capture.rs:9:29
   |
LL |     let bar: Box<_> = Box::new(3);
   |         --- captured outer variable
LL |     let _g = to_fn_mut(|| {
   |                        -- captured by this `FnMut` closure
LL |         let _h = to_fn_once(move || -> isize { *bar });
   |                             ^^^^^^^^^^^^^^^^   ----
   |                             |                  |
   |                             |                  variable moved due to use in closure
   |                             |                  move occurs because `bar` has type `Box<isize>`, which does not implement the `Copy` trait
   |                             `bar` is moved here
   |
help: clone the value before moving it into the closure
   |
LL ~         let value = bar.clone();
LL ~         let _h = to_fn_once(move || -> isize { value });
   |
```
2024-04-24 22:21:16 +00:00
Esteban Küber
d68f2a6b71 Mention when type parameter could be Clone
```
error[E0382]: use of moved value: `t`
  --> $DIR/use_of_moved_value_copy_suggestions.rs:7:9
   |
LL | fn duplicate_t<T>(t: T) -> (T, T) {
   |                   - move occurs because `t` has type `T`, which does not implement the `Copy` trait
...
LL |     (t, t)
   |      -  ^ value used here after move
   |      |
   |      value moved here
   |
help: if `T` implemented `Clone`, you could clone the value
  --> $DIR/use_of_moved_value_copy_suggestions.rs:4:16
   |
LL | fn duplicate_t<T>(t: T) -> (T, T) {
   |                ^ consider constraining this type parameter with `Clone`
...
LL |     (t, t)
   |      - you could clone this value
help: consider restricting type parameter `T`
   |
LL | fn duplicate_t<T: Copy>(t: T) -> (T, T) {
   |                 ++++++
```

The `help` is new. On ADTs, we also extend the output with span labels:

```
error[E0507]: cannot move out of static item `FOO`
  --> $DIR/issue-17718-static-move.rs:6:14
   |
LL |     let _a = FOO;
   |              ^^^ move occurs because `FOO` has type `Foo`, which does not implement the `Copy` trait
   |
note: if `Foo` implemented `Clone`, you could clone the value
  --> $DIR/issue-17718-static-move.rs:1:1
   |
LL | struct Foo;
   | ^^^^^^^^^^ consider implementing `Clone` for this type
...
LL |     let _a = FOO;
   |              --- you could clone this value
help: consider borrowing here
   |
LL |     let _a = &FOO;
   |              +
```
2024-04-24 22:21:15 +00:00
Esteban Küber
4aba2c55e6 Modify find_expr from Span to better account for closures
Start pointing to where bindings were declared when they are captured in closures:

```
error[E0597]: `x` does not live long enough
  --> $DIR/suggest-return-closure.rs:23:9
   |
LL |     let x = String::new();
   |         - binding `x` declared here
...
LL |     |c| {
   |     --- value captured here
LL |         x.push(c);
   |         ^ borrowed value does not live long enough
...
LL | }
   | -- borrow later used here
   | |
   | `x` dropped here while still borrowed
```

Suggest cloning in more cases involving closures:

```
error[E0507]: cannot move out of `foo` in pattern guard
  --> $DIR/issue-27282-move-ref-mut-into-guard.rs:11:19
   |
LL |             if { (|| { let mut bar = foo; bar.take() })(); false } => {},
   |                   ^^                 --- move occurs because `foo` has type `&mut Option<&i32>`, which does not implement the `Copy` trait
   |                   |
   |                   `foo` is moved here
   |
   = note: variables bound in patterns cannot be moved from until after the end of the pattern guard
help: consider cloning the value if the performance cost is acceptable
   |
LL |             if { (|| { let mut bar = foo.clone(); bar.take() })(); false } => {},
   |                                         ++++++++
```
2024-04-24 22:21:13 +00:00
yukang
be9dbe9102 Suggest ref mut for pattern matching assignment 2024-04-25 04:54:25 +08:00
León Orell Valerian Liehr
332cac2c6d
Rollup merge of #122598 - Nadrieril:full-derefpats, r=matthewjasper
deref patterns: lower deref patterns to MIR

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

The thing I'm not confident about is the handling of fake borrows. This PR ignores any fake borrows inside a deref pattern. We are guaranteed to at least fake borrow the place of the first pointer value, which could be enough, but I'm not certain.
2024-04-23 17:25:15 +02:00
Guillaume Gomez
e984447405
Rollup merge of #124183 - compiler-errors:unnecessary-by-ref, r=oli-obk
Stop taking `ParamTy`/`ParamConst`/`EarlyParamRegion`/`AliasTy` by ref

It's unnecessary and is annoying when we have it by value.
2024-04-22 20:25:59 +02:00
Scott McMurray
e6b2b764ec Add AggregateKind::RawPtr and enough support to compile 2024-04-21 11:08:37 -07:00
Nadrieril
50531806ee Add a non-shallow fake borrow 2024-04-20 16:01:35 +02:00
Michael Goulet
86756c1804 Stop taking ParamTy/ParamConst/EarlyParamRegion/AliasTy by ref 2024-04-19 21:09:51 -04:00
beepster4096
17073464ad remove optionality from MoveData::base_local 2024-04-19 16:50:46 -07:00
Jules Bertholet
2a4624ddd1
Rename BindingAnnotation to BindingMode 2024-04-17 09:34:39 -04:00
bors
3fba278231 Auto merge of #123537 - compiler-errors:shallow, r=lcnr
Simplify shallow resolver to just fold ty/consts

Probably faster than using a whole folder?
2024-04-16 21:59:36 +00:00
Guillaume Gomez
24cdb7ed56
Rollup merge of #123990 - compiler-errors:suggest-closure-ret-deref, r=oli-obk
Make `suggest_deref_closure_return` more idiomatic/easier to understand

The only functional change here really is just making it not use a fresh type variable for upvars. I'll point that out in the code.

The rest of the changes are just stylistic, because reading this code was really confusing me (variable names were vague, ways of accessing types were unidiomatic, order of operations was kind of strange, etc).

This is stacked on #123989.

r? oli-obk since you approved #122213
2024-04-16 15:19:14 +02:00
Guillaume Gomez
9da8f04da3
Rollup merge of #123797 - amandasystems:better-graphviz, r=oli-obk
Better graphviz output for SCCs and NLL constraints

This PR modifies the output for `-Z dump-mir-graphviz=yes`. Specifically, it changes the output of the files `.-------.nll.0.regioncx.all.dot` and `nll.0.regioncx.scc.dot` to be easier to read and contain some information that helped me during debugging. In particular:

- SCC indices are contracted to `SCC(n)` instead of `ConstraintSccIndex(n)` to compress the nodes
- SCC regions are in `{}` rather than `[]` (controversial since they are technically ordered by index, but I figured they're more sets than arrays conceptually since they're equivalence classes).
- For regions in other universes than the root, also show the region universe (as ?8/U1)
- For regions with external names, show the external name in parenthesis
- For the region graph where edges are locations, render the All variant of the enum without the file since it's extremely long and often destroys the rendering
- For region graph edge annotations for single locations, remove the wrapping around the Location variant and just add its contents since this can be unambiguously done

Example output (from the function `foo()` of `tests/ui/error-codes/E0582.rs`) for an SCC graph:
![a graph showing SCCs](https://github.com/rust-lang/rust/assets/102855/0b998338-0379-4829-b99e-d8105c094897)

...and for the constraints:
![a graph showing regions and their constraints](https://github.com/rust-lang/rust/assets/102855/e984c4ca-7aa2-4db2-9878-bf38fe8208d5)

This PR also gives `UniverseIndex`es the `is_root()` method since this is now an operation that happens three times in the borrowck crate.
2024-04-16 15:19:14 +02:00
Michael Goulet
00838b3140 Make suggest_deref_closure_return more idiomatic/easier to understand 2024-04-15 23:04:16 -04:00
León Orell Valerian Liehr
daa2ebc70c
Rollup merge of #123989 - compiler-errors:type-dependent-def-id, r=oli-obk
Just use `type_dependent_def_id` to figure out what the method is for an expr

The calls to `lookup_method_for_diagnostic` are overkill.

r? oli-obk
2024-04-16 01:12:39 +02:00
León Orell Valerian Liehr
9cc26b598a
Rollup merge of #123016 - compiler-errors:no-type-var-origin, r=lcnr
Remove `TypeVariableOriginKind` and `ConstVariableOriginKind`

It's annoying to have to import `TypeVariableOriginKind` just to fill it with `MiscVariable` for almost every use. Every other usage other than `TypeParameterDefinition` wasn't even used -- I can see how it may have been useful once for debugging, but I do quite a lot of typeck debugging and I've never really needed it.

So let's just remove it, and keep around the only useful thing which is the `DefId` of the param for `var_for_def`.

This is based on #123006, which removed the special use of `TypeVariableOriginKind::OpaqueInference`, which I'm pretty sure I was the one that added.

r? lcnr or re-roll to types
2024-04-16 01:12:36 +02:00
Michael Goulet
ecef296a03 Simplify shallow resolver to just fold ty/consts 2024-04-15 18:09:16 -04:00
Michael Goulet
98890be9c4 Rebase fallout 2024-04-15 17:37:56 -04:00
Michael Goulet
05bb3d2683 Just use type_dependent_def_id to figure out what the method is for an expr 2024-04-15 17:14:59 -04:00
Michael Goulet
34bce07e8e Remove TypeVariableOriginKind 2024-04-15 16:51:50 -04:00
Michael Goulet
20a5fb3b4a
Rollup merge of #123924 - compiler-errors:tuple-sugg, r=estebank
Fix various bugs in `ty_kind_suggestion`

Consolidates two implementations of `ty_kind_suggestion`
Fixes some misuse of the empty param-env
Fixes a problem where we suggested `(42)` instead of `(42,)` for tuple suggestions
Suggest a value when `return;`, making it consistent with `break;`
Fixes #123906
2024-04-15 15:18:06 -04:00
许杰友 Jieyou Xu (Joe)
5580ae9795
Rollup merge of #123934 - WaffleLapkin:graph-mini-refactor, r=fmease
`rustc_data_structures::graph` mini refactor

Who doesn't love to breathe dust from the ancient times?
2024-04-15 16:56:18 +01:00
Maybe Waffle
435db9b9bd Use RPITIT for Successors and Predecessors traits
Now with RPITIT instead of GAT!
2024-04-15 13:34:08 +00:00
Maybe Waffle
e8d2221e3b Make depth_first_search into a standalone function
Does not necessarily change much, but we never overwrite it, so I see no reason
for it to be in the `Successors` trait. (+we already have a similar `is_cyclic`)
2024-04-14 16:03:08 +00:00
Maybe Waffle
0d5fc9bf58 Merge {With,Graph}{Successors,Predecessors} into {Successors,Predecessors}
Now with GAT!
2024-04-14 15:48:53 +00:00
Maybe Waffle
398da593a5 Merge WithNumNodes into DirectedGraph 2024-04-14 15:46:40 +00:00
Michael Goulet
d6ac50e547 Consolidate two copies of ty_kind_suggestion 2024-04-14 09:42:53 -04:00
bors
6eaa7fb576 Auto merge of #122603 - estebank:clone-o-rama, r=lcnr
Detect borrow checker errors where `.clone()` would be an appropriate user action

When a value is moved twice, suggest cloning the earlier move:

```
error[E0509]: cannot move out of type `U2`, which implements the `Drop` trait
  --> $DIR/union-move.rs:49:18
   |
LL |         move_out(x.f1_nocopy);
   |                  ^^^^^^^^^^^
   |                  |
   |                  cannot move out of here
   |                  move occurs because `x.f1_nocopy` has type `ManuallyDrop<RefCell<i32>>`, which does not implement the `Copy` trait
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL |         move_out(x.f1_nocopy.clone());
   |                             ++++++++
```

When a value is borrowed by an `fn` call, consider if cloning the result of the call would be reasonable, and suggest cloning that, instead of the argument:

```
error[E0505]: cannot move out of `a` because it is borrowed
  --> $DIR/variance-issue-20533.rs:53:14
   |
LL |         let a = AffineU32(1);
   |             - binding `a` declared here
LL |         let x = bat(&a);
   |                     -- borrow of `a` occurs here
LL |         drop(a);
   |              ^ move out of `a` occurs here
LL |         drop(x);
   |              - borrow later used here
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL |         let x = bat(&a).clone();
   |                        ++++++++
```

otherwise, suggest cloning the argument:

```
error[E0505]: cannot move out of `a` because it is borrowed
  --> $DIR/variance-issue-20533.rs:59:14
   |
LL |         let a = ClonableAffineU32(1);
   |             - binding `a` declared here
LL |         let x = foo(&a);
   |                     -- borrow of `a` occurs here
LL |         drop(a);
   |              ^ move out of `a` occurs here
LL |         drop(x);
   |              - borrow later used here
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL -         let x = foo(&a);
LL +         let x = foo(a.clone());
   |
```

This suggestion doesn't attempt to square out the types between what's cloned and what the `fn` expects, to allow the user to make a determination on whether to change the `fn` call or `fn` definition themselves.

Special case move errors caused by `FnOnce`:

```
error[E0382]: use of moved value: `blk`
  --> $DIR/once-cant-call-twice-on-heap.rs:8:5
   |
LL | fn foo<F:FnOnce()>(blk: F) {
   |                    --- move occurs because `blk` has type `F`, which does not implement the `Copy` trait
LL |     blk();
   |     ----- `blk` moved due to this call
LL |     blk();
   |     ^^^ value used here after move
   |
note: `FnOnce` closures can only be called once
  --> $DIR/once-cant-call-twice-on-heap.rs:6:10
   |
LL | fn foo<F:FnOnce()>(blk: F) {
   |          ^^^^^^^^ `F` is made to be an `FnOnce` closure here
LL |     blk();
   |     ----- this value implements `FnOnce`, which causes it to be moved when called
```

Account for redundant `.clone()` calls in resulting suggestions:

```
error[E0507]: cannot move out of dereference of `S`
  --> $DIR/needs-clone-through-deref.rs:15:18
   |
LL |         for _ in self.clone().into_iter() {}
   |                  ^^^^^^^^^^^^ ----------- value moved due to this method call
   |                  |
   |                  move occurs because value has type `Vec<usize>`, which does not implement the `Copy` trait
   |
note: `into_iter` takes ownership of the receiver `self`, which moves value
  --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL
help: you can `clone` the value and consume it, but this might not be your desired behavior
   |
LL |         for _ in <Vec<usize> as Clone>::clone(&self).into_iter() {}
   |                  ++++++++++++++++++++++++++++++    ~
```

We use the presence of `&mut` values in a move error as a proxy for the user caring about side effects, so we don't emit a clone suggestion in that case:

```
error[E0505]: cannot move out of `s` because it is borrowed
  --> $DIR/borrowck-overloaded-index-move-index.rs:53:7
   |
LL |     let mut s = "hello".to_string();
   |         ----- binding `s` declared here
LL |     let rs = &mut s;
   |              ------ borrow of `s` occurs here
...
LL |     f[s] = 10;
   |       ^ move out of `s` occurs here
...
LL |     use_mut(rs);
   |             -- borrow later used here
```

We properly account for `foo += foo;` errors where we *don't* suggest `foo.clone() += foo;`, instead suggesting `foo += foo.clone();`.

---

Each commit can be reviewed in isolation. There are some "cleanup" commits, but kept them separate in order to show *why* specific changes were being made, and their effect on tests' output.

Fix #49693, CC #64167.
2024-04-13 09:07:26 +00:00
Esteban Küber
4c7213c888 review comments
Added comments and reworded messages
2024-04-12 20:57:07 +00:00
Esteban Küber
dea9b5031c Better account for more cases involving closures 2024-04-12 04:46:31 +00:00
Esteban Küber
3cdc6897c5 Fix rebase 2024-04-12 04:45:50 +00:00
Matthias Krüger
6f78bf2322
Rollup merge of #123599 - matthiaskrgr:rm, r=cjgillot
remove some things that do not need to be
2024-04-12 04:38:21 +02:00
Matthias Krüger
ec91d71a38
Rollup merge of #123523 - estebank:issue-123414, r=BoxyUwU
Account for trait/impl difference when suggesting changing argument from ref to mut ref

Do not ICE when encountering a lifetime error involving an argument with an immutable reference of a method that differs from the trait definition.

Fix #123414.
2024-04-11 22:38:54 +02:00
Matthias Krüger
f9ca213510 remove some things that do not need to be 2024-04-11 21:09:52 +02:00
Esteban Küber
d97d2fe744 Mention when the type of the moved value doesn't implement Clone 2024-04-11 16:41:42 +00:00
Esteban Küber
d578ac9e47 Account for move error in the spread operator on struct literals
We attempt to suggest an appropriate clone for move errors on expressions
like `S { ..s }` where a field isn't `Copy`. If we can't suggest, we still don't
emit the incorrect suggestion of `S { ..s }.clone()`.

```
error[E0509]: cannot move out of type `S<K>`, which implements the `Drop` trait
  --> $DIR/borrowck-struct-update-with-dtor.rs:28:19
   |
LL |         let _s2 = S { a: 2, ..s0 };
   |                   ^^^^^^^^^^^^^^^^
   |                   |
   |                   cannot move out of here
   |                   move occurs because `s0.c` has type `K`, which does not implement the `Copy` trait
   |
help: clone the value from the field instead of using the spread operator syntax
   |
LL |         let _s2 = S { a: 2, c: s0.c.clone(), ..s0 };
   |                           +++++++++++++++++
```
```
error[E0509]: cannot move out of type `S<()>`, which implements the `Drop` trait
  --> $DIR/borrowck-struct-update-with-dtor.rs:20:19
   |
LL |         let _s2 = S { a: 2, ..s0 };
   |                   ^^^^^^^^^^^^^^^^
   |                   |
   |                   cannot move out of here
   |                   move occurs because `s0.b` has type `B`, which does not implement the `Copy` trait
   |
note: `B` doesn't implement `Copy` or `Clone`
  --> $DIR/borrowck-struct-update-with-dtor.rs:4:1
   |
LL | struct B;
   | ^^^^^^^^
help: if `B` implemented `Clone`, you could clone the value from the field instead of using the spread operator syntax
   |
LL |         let _s2 = S { a: 2, b: s0.b.clone(), ..s0 };
   |                           +++++++++++++++++
```
2024-04-11 16:41:42 +00:00
Esteban Küber
4ca876b7a4 Better account for FnOnce in move errors
```
error[E0382]: use of moved value: `blk`
  --> $DIR/once-cant-call-twice-on-heap.rs:8:5
   |
LL | fn foo<F:FnOnce()>(blk: F) {
   |                    --- move occurs because `blk` has type `F`, which does not implement the `Copy` trait
LL |     blk();
   |     ----- `blk` moved due to this call
LL |     blk();
   |     ^^^ value used here after move
   |
note: `FnOnce` closures can only be called once
  --> $DIR/once-cant-call-twice-on-heap.rs:6:10
   |
LL | fn foo<F:FnOnce()>(blk: F) {
   |          ^^^^^^^^ `F` is made to be an `FnOnce` closure here
LL |     blk();
   |     ----- this value implements `FnOnce`, which causes it to be moved when called
```
2024-04-11 16:41:42 +00:00
Esteban Küber
dfe28debb9 Account for assign binops in clone suggestions
Explicitly look for `expr += other_expr;` and avoid suggesting
`expr.clone() += other_expr;`, instead suggesting `expr += other_expr.clone();`.
2024-04-11 16:41:41 +00:00
Esteban Küber
a1a3abb08f When possible, suggest cloning the result of a call instead of an argument
```
error[E0505]: cannot move out of `a` because it is borrowed
  --> $DIR/variance-issue-20533.rs:28:14
   |
LL |         let a = AffineU32(1);
   |             - binding `a` declared here
LL |         let x = foo(&a);
   |                     -- borrow of `a` occurs here
LL |         drop(a);
   |              ^ move out of `a` occurs here
LL |         drop(x);
   |              - borrow later used here
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL |         let x = foo(&a).clone();
   |                        ++++++++
```
2024-04-11 16:41:41 +00:00
Esteban Küber
7f7f6792f1 Do not recomment cloning explicit &mut expressions 2024-04-11 16:41:41 +00:00
Esteban Küber
5a7caa3174 Fix accuracy of T: Clone check in suggestion 2024-04-11 16:41:41 +00:00
Esteban Küber
259348cf7e Remove unnecessary argument from suggest_cloning 2024-04-11 16:41:41 +00:00
Esteban Küber
01b810e052 Silence redundant clone suggestion 2024-04-11 16:41:41 +00:00
Esteban Küber
065454dd1d More move error suggestions to clone
```
error[E0507]: cannot move out of `val`, a captured variable in an `FnMut` closure
  --> $DIR/issue-87456-point-to-closure.rs:10:28
   |
LL |     let val = String::new();
   |         --- captured outer variable
LL |
LL |     take_mut(|| {
   |              -- captured by this `FnMut` closure
LL |
LL |         let _foo: String = val;
   |                            ^^^ move occurs because `val` has type `String`, which does not implement the `Copy` trait
   |
help: consider borrowing here
   |
LL |         let _foo: String = &val;
   |                            +
help: consider cloning the value if the performance cost is acceptable
   |
LL |         let _foo: String = val.clone();
   |                               ++++++++
```
2024-04-11 16:41:41 +00:00
Esteban Küber
10c2fbec24 Suggest .clone() in some move errors
```
error[E0507]: cannot move out of `*x` which is behind a shared reference
  --> $DIR/borrowck-fn-in-const-a.rs:6:16
   |
LL |         return *x
   |                ^^ move occurs because `*x` has type `String`, which does not implement the `Copy` trait
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL -         return *x
LL +         return x.clone()
   |
```
2024-04-11 16:41:41 +00:00
Esteban Küber
bce78102c3 Account for unops when suggesting cloning 2024-04-11 16:41:41 +00:00
Esteban Küber
fa2fc3ab96 Suggest .clone() when moved while borrowed 2024-04-11 16:41:41 +00:00
Esteban Küber
5eb573a343 Account for .clone() when suggesting <T as Clone>::clone 2024-04-11 16:41:40 +00:00
Amanda Stjerna
800c50608c Slightly more readable NLL/constraint graph dumps 2024-04-11 17:14:35 +02:00
Matthias Krüger
93645f481d
Rollup merge of #123704 - estebank:diag-changes, r=compiler-errors
Tweak value suggestions in `borrowck` and `hir_analysis`

Unify the output of `suggest_assign_value` and `ty_kind_suggestion`.

Ideally we'd make these a single function, but doing so would likely require modify the crate dependency tree.
2024-04-11 09:31:50 +02:00
bors
08273780d8 Auto merge of #122213 - estebank:issue-50195, r=oli-obk,estebank
Provide suggestion to dereference closure tail if appropriate

When encoutnering a case like

```rust
use std::collections::HashMap;

fn main() {
    let vs = vec![0, 0, 1, 1, 3, 4, 5, 6, 3, 3, 3];

    let mut counts = HashMap::new();
    for num in vs {
        let count = counts.entry(num).or_insert(0);
        *count += 1;
    }

    let _ = counts.iter().max_by_key(|(_, v)| v);
```
produce the following suggestion
```
error: lifetime may not live long enough
  --> $DIR/return-value-lifetime-error.rs:13:47
   |
LL |     let _ = counts.iter().max_by_key(|(_, v)| v);
   |                                       ------- ^ returning this value requires that `'1` must outlive `'2`
   |                                       |     |
   |                                       |     return type of closure is &'2 &i32
   |                                       has type `&'1 (&i32, &i32)`
   |
help: dereference the return value
   |
LL |     let _ = counts.iter().max_by_key(|(_, v)| **v);
   |                                               ++
```

Fix #50195.
2024-04-11 02:37:35 +00:00
Esteban Küber
1eda0565fa Handle more cases of "values to suggest" given a type
Add handling for `String`, `Box`, `Option` and `Result`.
2024-04-10 23:58:36 +00:00
Esteban Küber
e17388b809 Handle more cases of value suggestions 2024-04-10 20:36:14 +00:00
Oli Scherer
f2465f8f20 Use trait solver to answer questions instead of manually writing a trait solver 2024-04-10 05:22:43 +00:00
Esteban Küber
a983dd8563 Tweak value suggestions in borrowck and hir_analysis
Unify the output of `suggest_assign_value` and `ty_kind_suggestion`.

Ideally we'd make these a single function, but doing so would likely require modify the crate dependency tree.
2024-04-09 23:37:13 +00:00
bors
b234e44944 Auto merge of #122077 - oli-obk:eager_opaque_checks4, r=lcnr
Pass list of defineable opaque types into canonical queries

This eliminates `DefiningAnchor::Bubble` for good and brings the old solver closer to the new one wrt cycles and nested obligations. At that point the difference between `DefiningAnchor::Bind([])` and `DefiningAnchor::Error` was academic. We only used the difference for some sanity checks, which actually had to be worked around in places, so I just removed `DefiningAnchor` entirely and just stored the list of opaques that may be defined.

fixes #108498
fixes https://github.com/rust-lang/rust/issues/116877

* [x] run crater
  - https://github.com/rust-lang/rust/pull/122077#issuecomment-2013293931
2024-04-08 23:01:50 +00:00
Oli Scherer
2f2350e577 Eliminate DefiningAnchor now that is just a single-variant enum 2024-04-08 15:00:27 +00:00
Oli Scherer
b2b5fa825d Eagerly check for accidentally registered region constraints instead of waiting until borrowck is done 2024-04-08 15:00:26 +00:00
Oli Scherer
19bd91d128 Pass list of defineable opaque types into canonical queries 2024-04-08 15:00:26 +00:00
Oli Scherer
84acfe86de Actually create ranged int types in the type system. 2024-04-08 12:02:19 +00:00
Esteban Küber
731c0e59a4 Account for trait/impl difference when suggesting changing argument from ref to mut ref
Do not ICE when encountering a lifetime error involving an argument with
an immutable reference of a method that differs from the trait definition.

Fix #123414.
2024-04-06 16:23:10 +00:00
Esteban Küber
9de6b70bb6 Provide suggestion to dereference closure tail if appropriate
When encoutnering a case like

```rust
//@ run-rustfix
use std::collections::HashMap;

fn main() {
    let vs = vec![0, 0, 1, 1, 3, 4, 5, 6, 3, 3, 3];

    let mut counts = HashMap::new();
    for num in vs {
        let count = counts.entry(num).or_insert(0);
        *count += 1;
    }

    let _ = counts.iter().max_by_key(|(_, v)| v);
```
produce the following suggestion
```
error: lifetime may not live long enough
  --> $DIR/return-value-lifetime-error.rs:13:47
   |
LL |     let _ = counts.iter().max_by_key(|(_, v)| v);
   |                                       ------- ^ returning this value requires that `'1` must outlive `'2`
   |                                       |     |
   |                                       |     return type of closure is &'2 &i32
   |                                       has type `&'1 (&i32, &i32)`
   |
help: dereference the return value
   |
LL |     let _ = counts.iter().max_by_key(|(_, v)| **v);
   |                                               ++
```

Fix #50195.
2024-04-05 19:42:55 +00:00
Matthias Krüger
25b0e84170
Rollup merge of #123419 - petrochenkov:zeroindex, r=compiler-errors
rustc_index: Add a `ZERO` constant to index types

It is commonly used.
2024-04-03 22:11:02 +02:00
Vadim Petrochenkov
b40ea03f8a rustc_index: Add a ZERO constant to index types
It is commonly used.
2024-04-03 19:06:22 +03:00
joboet
989660c3e6
rename expose_addr to expose_provenance 2024-04-03 16:00:38 +02:00
Jacob Pratt
e9ef8e1efa
Rollup merge of #122935 - RalfJung:with-exposed-provenance, r=Amanieu
rename ptr::from_exposed_addr -> ptr::with_exposed_provenance

As discussed on [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-opsem/topic/To.20expose.20or.20not.20to.20expose/near/427757066).

The old name, `from_exposed_addr`, makes little sense as it's not the address that is exposed, it's the provenance. (`ptr.expose_addr()` stays unchanged as we haven't found a better option yet. The intended interpretation is "expose the provenance and return the address".)

The new name nicely matches `ptr::without_provenance`.
2024-04-02 20:37:39 -04:00
Michael Goulet
bda301ead8 Stop calling visitors V 2024-03-30 11:13:33 -04:00
Matthias Krüger
8d820c0c47
Rollup merge of #123188 - klensy:clippy-me2, r=Nilstrieb
compiler: fix few unused_peekable and needless_pass_by_ref_mut clippy lints

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

Better reviewed commit by commit, as fixes splitted by chunks.
2024-03-29 15:17:11 +01:00
bors
45796d1c24 Auto merge of #123080 - Jules-Bertholet:mut-ref-mut, r=Nadrieril
Match ergonomics 2024: implement mutable by-reference bindings

Implements the mutable by-reference bindings portion of match ergonomics 2024 (#123076), with the `mut ref`/`mut ref mut` syntax, under feature gate `mut_ref`.

r? `@Nadrieril`

`@rustbot` label A-patterns A-edition-2024
2024-03-29 11:08:11 +00:00
klensy
9a6b3dfc06 and few more
maybe bug here?

warning: this argument is a mutable reference, but not used mutably
    --> compiler\rustc_borrowck\src\diagnostics\conflict_errors.rs:3857:35
     |
3857 |     pub(crate) fn emit(&self, cx: &mut MirBorrowckCtxt<'_, 'tcx>, diag: &mut Diag<'_>) -> String {
     |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&MirBorrowckCtxt<'_, 'tcx>`
     |
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut

warning: this argument is a mutable reference, but not used mutably
   --> compiler\rustc_borrowck\src\type_check\liveness\trace.rs:601:17
    |
601 |         typeck: &mut TypeChecker<'_, 'tcx>,
    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&TypeChecker<'_, 'tcx>`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut
2024-03-28 16:57:32 +03:00