Commit Graph

4124 Commits

Author SHA1 Message Date
Michael Goulet
b58f5a7800 Don't ICE when we cannot eval a const to a valtree in the new solver 2024-05-07 11:14:25 -04:00
Matthias Krüger
284b5530b8
Rollup merge of #124809 - lcnr:prepopulate-opaques, r=compiler-errors
borrowck: prepopulate opaque storage more eagerly

otherwise we ICE due to ambiguity when normalizing while computing implied bounds.

r? ``@compiler-errors``
2024-05-06 21:46:06 +02:00
Matthias Krüger
f76c8f7f77
Rollup merge of #124759 - compiler-errors:impl-args, r=lcnr
Record impl args in the proof tree in new solver

Rather than rematching them during select.

Also use `ImplSource::Param` instead of `ImplSource::Builtin` for alias-bound candidates, so we don't ICE in `Instance::resolve`.

r? lcnr
2024-05-06 21:46:05 +02:00
Michael Goulet
e34723997a Use correct ImplSource for alias bounds 2024-05-06 14:38:35 -04:00
Michael Goulet
207b4b8e88 Record impl args in the InsepctCandiate rather than rematching during select 2024-05-06 14:17:22 -04:00
Matthias Krüger
43de8225dc
Rollup merge of #124771 - compiler-errors:cand-has-failing-wc, r=lcnr
Don't consider candidates with no failing where clauses when refining obligation causes in new solver

Improves error messages when we have param-env candidates that don't deeply unify (i.e. after alias-bounds).

r? lcnr
2024-05-06 18:50:35 +02:00
Matthias Krüger
2d557ba9f4
Rollup merge of #124724 - compiler-errors:prefer-lower, r=lcnr
Prefer lower vtable candidates in select in new solver

Also, adjust the select visitor to only winnow when the *parent* goal is `Certainty::Yes`. This means that we won't winnow in cases when we have any ambiguous inference guidance from two candidates.

r? lcnr
2024-05-06 18:50:35 +02:00
lcnr
5714c1f364 switch new solver to directly inject opaque types 2024-05-06 16:19:32 +00:00
Michael Goulet
4e3350d43b Don't consider candidates with no failing where clauses 2024-05-06 11:32:50 -04:00
Michael Goulet
a4ee20eb13 Prefer lower vtable candidates in select in new solver 2024-05-06 10:48:39 -04:00
Matthias Krüger
07dc4aa837
Rollup merge of #124718 - compiler-errors:record-impl-args, r=lcnr
Record impl args in the proof tree

Weren't recording these since they went through a different infcx method

r? lcnr
2024-05-04 22:27:33 +02:00
Matthias Krüger
79071ee3a9
Rollup merge of #124717 - compiler-errors:do-not-recomment-next-solver, r=lcnr
Implement `do_not_recommend` in the new solver

Put the test into `diagnostic_namespace` test folder even though it's not in the diagnostic namespace, because it should be soon.

r? lcnr
cc `@weiznich`
2024-05-04 22:27:32 +02:00
Michael Goulet
50338aa59a Record impl args in the proof tree 2024-05-04 12:57:01 -04:00
Michael Goulet
b33599485b Implement do_not_recommend in the new solver 2024-05-04 12:51:10 -04:00
Michael Goulet
6714216eaa Only consider ambiguous goals when finding best obligation for ambiguities 2024-05-04 12:05:36 -04:00
Michael Goulet
e3bf0a13cf
Rollup merge of #124418 - compiler-errors:better-cause, r=lcnr
Use a proof tree visitor to refine the `Obligation` for error reporting in new solver

With the magic of `ProofTreeVisitor`, we can close the gap that we have on `ObligationCause`s being not as descriptive in the new trait solver.

r? lcnr

Needs some work and obviously documentation.
2024-05-03 23:34:21 -04:00
Esteban Küber
4847f2249f Do not ICE on foreign malformed diagnostic::on_unimplemented
Fix #124651.
2024-05-03 21:53:19 +00:00
Michael Goulet
92861517aa Take ocx by move for pending obligations 2024-05-02 22:03:01 -04:00
Michael Goulet
d9eb5232b6 Use ObligationCtxt in favor of TraitEngine in many places 2024-05-02 22:03:01 -04:00
Michael Goulet
34e91ece90 Higher ranked goal source, do overflow handling less badly 2024-05-02 21:56:14 -04:00
Michael Goulet
3e03b1b190 Use a proof tree visitor to refine the Obligation for error reporting 2024-05-02 21:56:14 -04:00
Michael Goulet
382d0f73ad Record more kinds of things as impl where bounds 2024-05-02 21:56:14 -04:00
Michael Goulet
6e3808e274 Store goal source in InspectGoal 2024-05-02 21:56:14 -04:00
Michael Goulet
837bde11a2 Record certainty before evaluating nesteds, so we make candidates 2024-05-02 21:56:14 -04:00
Matthias Krüger
d6940fb43d
Rollup merge of #124624 - WaffleLapkin:old_unit, r=fmease
Use `tcx.types.unit` instead of `Ty::new_unit(tcx)`

I don't think there is any need for the function, given that we can just access the `.types`, similarly to all other primitives?
2024-05-02 19:42:50 +02:00
Waffle Lapkin
698d7a031e Inline & delete Ty::new_unit, since it's just a field access 2024-05-02 17:49:23 +02:00
lcnr
c4e882fd99 shallow resolve in orphan check 2024-05-02 15:44:05 +00:00
bors
f5efc3c286 Auto merge of #124521 - Mark-Simulacrum:bootstrap-bump, r=albertlarsan68
Bump bootstrap compiler to latest beta

https://forge.rust-lang.org/release/process.html#master-bootstrap-update-t-2-day-tuesday

This also cherry-picks d716d72586548963f32e5c8d57c41db0065fa6e0 from the beta branching, to continue to workaround #122758.

r? bootstrap
2024-05-02 09:21:43 +00:00
Mark Rousskov
a64f941611 Step bootstrap cfgs 2024-05-01 22:19:11 -04:00
bors
f92d49b7fe Auto merge of #124529 - compiler-errors:select, r=lcnr
Rewrite select (in the new solver) to use a `ProofTreeVisitor`

We can use a proof tree visitor rather than collecting and recomputing all the nested goals ourselves.

Based on #124415
2024-05-02 00:36:38 +00:00
Michael Goulet
9834c8307f Rewrite select to use a ProofTreeVisitor 2024-05-01 14:19:34 -04:00
Matthias Krüger
0dbe07f201
Rollup merge of #124566 - lcnr:normalizes-to-proof-tree, r=compiler-errors
fix `NormalizesTo` proof tree issue

fixes #124422
cc #121848

r? ``@compiler-errors``
2024-05-01 20:05:26 +02:00
lcnr
f323f9dedb review 2024-05-01 15:03:15 +00:00
bors
f5355b93ba Auto merge of #124356 - fmease:fewer-magic-numbers-in-names, r=lcnr
Cleanup: Replace item names referencing GitHub issues or error codes with something more meaningful

**lcnr** in https://github.com/rust-lang/rust/pull/117164#pullrequestreview-1969935387:

> […] while I know that there's precendent to name things `Issue69420`, I really dislike this as it requires looking up the issue to figure out the purpose of such a variant. Actually referring to the underlying issue, e.g. `AliasMayNormToUncovered` or whatever and then linking to the issue in a doc comment feels a lot more desirable to me. We should ideally rename all the functions and enums which currently use issue numbers.

I've grepped through `compiler/` like crazy and think that I've found all instances of this pattern.
However, I haven't renamed `compute_2229_migrations_*`. Should I?

The first commit introduces an abhorrent and super long name for an item because naming is hard but also scary looking / unwelcoming names are good for things related to temporary-ish backcompat hacks. I'll let you discover it by yourself.

Contains a bit of drive-by cleanup and a diag migration bc that was the simplest option.

r? lcnr or compiler
2024-05-01 00:04:36 +00:00
bors
f705de5962 Auto merge of #117164 - fmease:orphan-norm, r=lcnr
Lazily normalize inside trait ref during orphan check & consider ty params in rigid alias types to be uncovered

Fixes #99554, fixes rust-lang/types-team#104.
Fixes #114061.

Supersedes #100555.

Tracking issue for the future compatibility lint: #124559.

r? lcnr
2024-04-30 20:51:46 +00:00
León Orell Valerian Liehr
9e739b723b
Give items related to issue 33140 a more meaningful name 2024-04-30 22:27:19 +02:00
lcnr
da969d41a3 fix NormalizesTo proof tree issue 2024-04-30 20:03:33 +00:00
León Orell Valerian Liehr
951e902562
Normalize trait ref before orphan check & consider ty params in alias types to be uncovered 2024-04-30 21:54:54 +02: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
Michael Goulet
7597d1504e Split out instantiate_nested_goals 2024-04-29 17:06:34 -04:00
Michael Goulet
13825dcc15 Take proof trees by value in inspect goal 2024-04-29 17:06:34 -04:00
Michael Goulet
2eb7c8196b Only register candidate if it is associated w a shallow certainty 2024-04-29 10:25:51 -04:00
Michael Goulet
7cf1c547c2 Actually use probes when needed and stop relying on existing outer probes 2024-04-29 10:25:51 -04:00
Michael Goulet
5776aec662 Make names more accurate 2024-04-29 10:25:05 -04:00
Nicholas Nethercote
52e9a23bdc Remove extern crate smallvec from a couple of crates. 2024-04-29 18:47:54 +10:00
Nicholas Nethercote
7418aa1a07 Remove extern crate rustc_data_structures from numerous crates. 2024-04-29 18:45:14 +10:00
Nicholas Nethercote
4814fd0a4b Remove extern crate rustc_macros from numerous crates. 2024-04-29 10:21:54 +10:00
Michael Goulet
17728a9bb2 Record certainty of evaluate_added_goals_and_make_canonical_response call in candidate 2024-04-27 17:46:29 -04:00
bors
1b3a32958b Auto merge of #122385 - lcnr:analyze-obligations-for-infer, r=compiler-errors
`obligations_for_self_ty`: use `ProofTreeVisitor` for nested goals

As always, dealing with proof trees continues to be a hacked together mess. After this PR and #124380 the only remaining blocker for core is https://github.com/rust-lang/trait-system-refactor-initiative/issues/90. There is also a `ProofTreeVisitor` issue causing an ICE when compiling `alloc` which I will handle in a separate PR. This issue likely affects coherence diagnostics more generally.

The core idea is to extend the proof tree visitor to support visiting nested candidates without using a `probe`. We then simply recurse into nested candidates if they are the only potentially applicable candidate for a given goal and check whether the self type matches the expected one.

For that to work, we need to improve `CanonicalState` to also handle unconstrained inference variables created inside of the trait solver. This is done by extending the `var_values` of `CanoncalState` with each fresh inference variables. Furthermore, we also store the state of all inference variables at the end of each probe. When recursing into `InspectCandidates` we then unify the values of all these states.

r? `@compiler-errors`
2024-04-26 15:37:05 +00:00
Michael Goulet
88eae31261
Rollup merge of #124381 - compiler-errors:derived-for-wf, r=lcnr
Renamed `DerivedObligation` to `WellFormedDeriveObligation`

It's used when computing `WellFormed` obligations, so let's give it a less ambiguous name.
2024-04-25 20:07:41 -04:00
Michael Goulet
4494140244
Rollup merge of #124379 - compiler-errors:remove-new-solver-lookup-behavior, r=lcnr
Remove special-casing for `SimplifiedType` for next solver

It's unnecessary due to the way that we fully normalize the self type before assembly begins.

r? lcnr
2024-04-25 20:07:41 -04:00
Michael Goulet
132f8ce3dc Renamed DerivedObligation to WellFormedDeriveObligation 2024-04-25 16:55:15 -04:00
lcnr
b64f687cb0 use EagerResolver 2024-04-25 20:19:01 +00:00
lcnr
03878c682a hir typeck: look into nested goals
uses a `ProofTreeVisitor` to look into nested
goals when looking at the pending obligations
during hir typeck. Used by closure signature
inference, coercion, and for async functions.
2024-04-25 19:44:00 +00:00
Michael Goulet
f2518cd798 Remove special-casing for SimplifiedType for next solver 2024-04-25 14:27:39 -04: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
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
León Orell Valerian Liehr
6e423e1651
Rollup merge of #124218 - Xiretza:subsubdiagnostics, r=davidtwco
Allow nesting subdiagnostics in #[derive(Subdiagnostic)]
2024-04-23 17:25:17 +02:00
León Orell Valerian Liehr
80f2b91b20
Rollup merge of #120929 - long-long-float:wrap-dyn-in-suggestion, r=fmease
Wrap dyn type with parentheses in suggestion

Close #120223

Fix wrong suggestion that is grammatically incorrect.
Specifically, I added parentheses to dyn types that need lifetime bound.

```
help: consider adding an explicit lifetime bound
  |
4 |     executor: impl FnOnce(T) -> (dyn Future<Output = ()>) + 'static,
  |                                 +                       +++++++++++
```
2024-04-23 17:25:14 +02:00
Matthias Krüger
326cd5cb68
Rollup merge of #124168 - oli-obk:define_opaque_types12, r=lcnr
Use `DefiningOpaqueTypes::Yes` in rustdoc, where the `InferCtxt` is guaranteed to have no opaque types it can define

r? `@lcnr`

I manually checked there it's always `tcx.infer_ctxt().build()`
2024-04-23 06:24:56 +02:00
bors
aca749eefc Auto merge of #121801 - zetanumbers:async_drop_glue, r=oli-obk
Add simple async drop glue generation

This is a prototype of the async drop glue generation for some simple types. Async drop glue is intended to behave very similar to the regular drop glue except for being asynchronous. Currently it does not execute synchronous drops but only calls user implementations of `AsyncDrop::async_drop` associative function and awaits the returned future. It is not complete as it only recurses into arrays, slices, tuples, and structs and does not have same sensible restrictions as the old `Drop` trait implementation like having the same bounds as the type definition, while code assumes their existence (requires a future work).

This current design uses a workaround as it does not create any custom async destructor state machine types for ADTs, but instead uses types defined in the std library called future combinators (deferred_async_drop, chain, ready_unit).

Also I recommend reading my [explainer](https://zetanumbers.github.io/book/async-drop-design.html).

This is a part of the [MCP: Low level components for async drop](https://github.com/rust-lang/compiler-team/issues/727) work.

Feature completeness:

 - [x] `AsyncDrop` trait
 - [ ] `async_drop_in_place_raw`/async drop glue generation support for
   - [x] Trivially destructible types (integers, bools, floats, string slices, pointers, references, etc.)
   - [x] Arrays and slices (array pointer is unsized into slice pointer)
   - [x] ADTs (enums, structs, unions)
   - [x] tuple-like types (tuples, closures)
   - [ ] Dynamic types (`dyn Trait`, see explainer's [proposed design](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#async-drop-glue-for-dyn-trait))
   - [ ] coroutines (https://github.com/rust-lang/rust/pull/123948)
 - [x] Async drop glue includes sync drop glue code
 - [x] Cleanup branch generation for `async_drop_in_place_raw`
 - [ ] Union rejects non-trivially async destructible fields
 - [ ] `AsyncDrop` implementation requires same bounds as type definition
 - [ ] Skip trivially destructible fields (optimization)
 - [ ] New [`TyKind::AdtAsyncDestructor`](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#adt-async-destructor-types) and get rid of combinators
 - [ ] [Synchronously undroppable types](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#exclusively-async-drop)
 - [ ] Automatic async drop at the end of the scope in async context
2024-04-23 02:10:23 +00: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
long-long-float
31e581ec12 Wrap dyn type with parentheses in suggestion 2024-04-23 00:15:10 +09:00
Oli Scherer
6bff7f45f1 Use DefiningOpaqueTypes::Yes, as the InferCtxt we use has no opaque types it may define 2024-04-22 13:11:29 +00:00
Daria Sukhonina
a9c7465997 Fix copy-paste typo in the comment within consider_builtin_async_destruct_candidate 2024-04-22 15:42:07 +03:00
Daria Sukhonina
0881e3e531 Exhaustivelly match TyKind in consider_builtin_async_destruct_candidate 2024-04-22 15:41:08 +03:00
Xiretza
5646b65cf5 Pass translation closure to add_to_diag_with() as reference 2024-04-21 07:45:03 +00:00
Lukas Markeffsky
31a05a227a merge two impl blocks 2024-04-20 18:24:54 +02:00
Lukas Markeffsky
f9ba863c4d remove InferCtxt::clear_caches 2024-04-20 16:43:00 +02:00
Lukas Markeffsky
88b10c1162 include ParamEnv in projection cache key 2024-04-20 16:42:18 +02:00
Michael Goulet
86756c1804 Stop taking ParamTy/ParamConst/EarlyParamRegion/AliasTy by ref 2024-04-19 21:09:51 -04:00
Oli Scherer
dadece067e Let inherent associated types constrain opaque types during projection 2024-04-19 16:12:54 +00:00
bors
c25473ff62 Auto merge of #124008 - nnethercote:simpler-static_assert_size, r=Nilstrieb
Simplify `static_assert_size`s.

We want to run them on all 64-bit platforms.

r? `@ghost`
2024-04-18 09:47:45 +00:00
Nicholas Nethercote
0d97669a17 Simplify static_assert_sizes.
We want to run them on all 64-bit platforms.
2024-04-18 15:36:25 +10:00
Daria Sukhonina
80c0b7e90f Use non-exhaustive matches for TyKind
Also no longer export noop async_drop_in_place_raw
2024-04-17 20:49:53 +03:00
Jules Bertholet
2a4624ddd1
Rename BindingAnnotation to BindingMode 2024-04-17 09:34:39 -04:00
Matthias Krüger
45940fe6d8
Rollup merge of #122813 - nnethercote:nicer-quals, r=compiler-errors
Qualifier tweaking

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

r? `@compiler-errors`
2024-04-17 05:44:52 +02:00
bors
7e3ba5b8b7 Auto merge of #124040 - GuillaumeGomez:rollup-hrrvsgh, r=GuillaumeGomez
Rollup of 7 pull requests

Successful merges:

 - #123673 (Don't ICE for kind mismatches during error rendering)
 - #123675 (Taint const qualifs if a static is referenced that didn't pass wfcheck)
 - #123975 (Port the 2 `rust-lld` run-make tests to `rmake`)
 - #124000 (Use `/* value */` as a placeholder)
 - #124013 (Box::into_raw: make Miri understand that this is a box-to-raw cast)
 - #124027 (Prefer identity equality over equating types during coercion.)
 - #124036 (Remove `default_hidden_visibility: false` from wasm targets)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-17 00:04:40 +00:00
Guillaume Gomez
4764dceb0f
Rollup merge of #124000 - compiler-errors:sugg-tweaks, r=wesleywiser
Use `/* value */` as a placeholder

The expression `value` isn't a valid suggestion; let's use `/* value */` as a placeholder (which is also invalid) since it more clearly signals to the user that they need to fill it in with something meaningful. This parallels the suggestions we have in a couple other places, like arguments.

We could also print the type name instead of `/* value */`, especially if it's suggestable, but I don't care strongly about that.
2024-04-17 00:00:23 +02:00
Guillaume Gomez
4aaa8f964f
Rollup merge of #123673 - oli-obk:sig_wfcheck_ice, r=jieyouxu,estebank
Don't ICE for kind mismatches during error rendering

fixes #123457

also some test suite cleanups to make backtraces easier to read
2024-04-17 00:00:22 +02: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
zetanumbers
24a24ec6ba Add simple async drop glue generation
Explainer: https://zetanumbers.github.io/book/async-drop-design.html

https://github.com/rust-lang/rust/pull/121801
2024-04-16 20:45:07 +03:00
Oli Scherer
0a88339a57 Don't ICE for kind mismatches during error rendering 2024-04-16 11:52:12 +00:00
Gurinder Singh
c30e15aded Fail candidate assembly for erroneous types
Trait predicates for types which have errors may still
evaluate to OK leading to downstream ICEs. Now we return
a selection error for such types in candidate assembly and
thereby prevent such issues
2024-04-16 12:42:48 +05:30
Nicholas Nethercote
4b27cc8b7a Avoid lots of hir::HirId{,Map,Set} qualifiers.
Because they're a bit redundant.
2024-04-16 16:29:15 +10:00
Nicholas Nethercote
27374a0214 Avoid unnecessary rustc_span::DUMMY_SP usage.
In some cases `DUMMY_SP` is already imported. In other cases this commit
adds the necessary import, in files where `DUMMY_SP` is used more than
once.
2024-04-16 15:55:24 +10:00
Michael Goulet
c95761385e Make array suggestions slightly more accurate 2024-04-15 21:45:47 -04:00
Michael Goulet
8a981b6fee Use /* value */ as a placeholder 2024-04-15 21:36:52 -04: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
eb6f856169 Remove ConstVariableOriginKind 2024-04-15 16:52:12 -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
Michael Goulet
314dee528b
Rollup merge of #123900 - compiler-errors:nobound, r=lcnr
Stop using `PolyTraitRef` for closure/coroutine predicates already instantiated w placeholders

r? lcnr
2024-04-15 15:18:05 -04:00
Michael Goulet
9e630d3f21 PolyTraitRefs -> TraitRefs 2024-04-15 12:04:44 -04:00
Michael Goulet
d2ec957680 Stop using PolyTraitRef for closure/coroutine predicates already instantiated w placeholders 2024-04-15 10:32:21 -04:00
Guillaume Gomez
86b791a272
Rollup merge of #123618 - compiler-errors:overflow-ambig, r=spastorino
Discard overflow obligations in `impl_may_apply`

Hacky fix for #123493. Throws away obligations that are overflowing in `impl_may_apply` when we recompute if an impl applies, since those will lead to fatal overflow if processed during fulfillment.

Something about #114811 (I think it's the predicate reordering) caused us to evaluate predicates differently in error reporting leading to fatal overflow, though I believe the underlying overflow is possible to hit since this code was rewritten to use fulfillment.

Fixes #123493
2024-04-14 23:24:33 +02:00
Michael Goulet
325b24d763 Fix 1-tuple value suggestion 2024-04-14 09:42:53 -04:00
Michael Goulet
e4c71f1fd8 Fix value suggestion for array in generic context 2024-04-14 09:42:53 -04:00
Michael Goulet
d6ac50e547 Consolidate two copies of ty_kind_suggestion 2024-04-14 09:42:53 -04:00
Michael Goulet
3253c021cb Add a helper for extending a span to include any trailing whitespace 2024-04-09 14:06:09 -04:00
Guillaume Gomez
e5b2935dc1
Rollup merge of #123662 - compiler-errors:no-upvars-yet, r=oli-obk
Don't rely on upvars being assigned just because coroutine-closure kind is assigned

Previously, code relied on the implicit assumption that if a coroutine-closure's kind variable was constrained, then its upvars were also constrained. This is because we assign all of them at once at the end up upvar analysis.

However, there's another way that a coroutine-closure's kind can be constrained: from a signature hint in closure signature deduction. After #123350, we use these hints, which means the implicit assumption above no longer holds.

This PR adds the necessary checks so that we don't ICE.

r? oli-obk
2024-04-09 13:39:23 +02:00
Michael Goulet
6f96d7d012 Don't rely on upvars being assigned just because coroutine-closure kind is assigned 2024-04-08 22:43:32 -04: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
Matthias Krüger
984767e500
Rollup merge of #123578 - lqd:regression-123275, r=compiler-errors
Restore `pred_known_to_hold_modulo_regions`

As requested by `@lcnr` in https://github.com/rust-lang/rust/issues/123275#issuecomment-2031885563 this PR restores `pred_known_to_hold_modulo_regions` to fix that "unexpected unsized tail" beta regression.

This also adds the reduced repro from https://github.com/rust-lang/rust/issues/123275#issuecomment-2041222851 as a sub-optimal test is better than no test at all, and it'll also cover #108721. It still ICEs on master, even though https://github.com/phlip9/rustc-warp-ice doesn't on nightly anymore, since https://github.com/rust-lang/rust/pull/122493.

Fixes #123275.

r? `@compiler-errors` but feel free to close if you'd rather have a better test instead
cc `@wesleywiser` who had signed up to do the revert

Will need a backport if we go with this PR: `@rustbot` label +beta-nominated
2024-04-08 22:06:23 +02:00
Matthias Krüger
0e27c99332
Rollup merge of #123367 - jswrenn:layoutify, r=compiler-errors
Safe Transmute: Compute transmutability from `rustc_target::abi::Layout`

In its first step of computing transmutability, `rustc_transmutability` constructs a byte-level representation of type layout (`Tree`). Previously, this representation was computed for ADTs by inspecting the ADT definition and performing our own layout computations. This process was error-prone, verbose, and limited our ability to analyze many types (particularly default-repr types).

In this PR, we instead construct `Tree`s from `rustc_target::abi::Layout`s. This helps ensure that layout optimizations are reflected our analyses, and increases the kinds of types we can now analyze, including:
- default repr ADTs
- transparent unions
- `UnsafeCell`-containing types

Overall, this PR expands the expressvity of `rustc_transmutability` to be much closer to the transmutability analysis performed by miri. Future PRs will work to close the remaining gaps (e.g., support for `Box`, raw pointers, `NonZero*`, coroutines, etc.).

r? `@compiler-errors`
2024-04-08 22:06:21 +02:00
Jack Wrenn
3aa14e3b2e Compute transmutability from rustc_target::abi::Layout
In its first step of computing transmutability, `rustc_transmutability`
constructs a byte-level representation of type layout (`Tree`). Previously, this
representation was computed for ADTs by inspecting the ADT definition and
performing our own layout computations. This process was error-prone, verbose,
and limited our ability to analyze many types (particularly default-repr types).

In this PR, we instead construct `Tree`s from `rustc_target::abi::Layout`s. This
helps ensure that layout optimizations are reflected our analyses, and increases
the kinds of types we can now analyze, including:
- default repr ADTs
- transparent unions
- `UnsafeCell`-containing types

Overall, this PR expands the expressvity of `rustc_transmutability` to be much
closer to the transmutability analysis performed by miri. Future PRs will work
to close the remaining gaps (e.g., support for `Box`, raw pointers, `NonZero*`,
coroutines, etc.).
2024-04-08 15:36:52 +00:00
Oli Scherer
7cfa521931 Avoid fetching the opaque type origin when only "is this in the defining scope" is actually needed 2024-04-08 15:01:21 +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
dd72bf922a Scrape extraneous regions from instantiate_nll_query_response_and_region_obligations 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
Michael Goulet
87a387a722 Discard overflow obligations in impl_may_apply 2024-04-07 23:21:45 -04:00
Rémy Rakic
68b4257ccf Revert "remove pred_known_to_hold_modulo_regions"
This reverts commit 399a258f46.
2024-04-06 23:29:59 +00:00
Santiago Pastorino
60be29bec8
Add a debug asserts call to match_projection_projections to ensure invariant 2024-04-06 14:45:48 -03:00
bors
8d490e33ad Auto merge of #123471 - compiler-errors:match_projection_projections, r=oli-obk
Check def id before calling `match_projection_projections`

When I "inlined" `assemble_candidates_from_predicates` into `for_each_item_bound` in #120584, I forgot to copy over the check that actually made sure the def id of the candidate was equal to the def id of the obligation. This means that we normalize goal a bit too often even if it's not productive to do so.

This PR adds that def id check back.
Fixes #123448
2024-04-06 06:36:42 +00:00
bors
9d79cd5f79 Auto merge of #122747 - Urgau:non-local-defs_perfect_impl, r=lcnr
Implement T-types suggested logic for perfect non-local impl detection

This implement [T-types suggested logic](https://github.com/rust-lang/rust/issues/121621#issuecomment-1976826895) for perfect non-local impl detection:

> for each impl, instantiate all local types with inference vars and then assemble candidates for that goal, if there are more than 1 (non-private impls), it does not leak

This extension to the current logic is meant to address issues reported in https://github.com/rust-lang/rust/issues/121621.

This PR also re-enables the lint `non_local_definitions` to warn-by-default.

Implementation was discussed in this [zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/144729-t-types/topic/Implementing.20new.20non-local.20impl.20defs.20logic).

Fixes https://github.com/rust-lang/rust/issues/121621
Fixes https://github.com/rust-lang/rust/issues/121746

r? `@lcnr` *(feel free to re-roll)*
2024-04-05 20:09:57 +00:00
Urgau
617324095b Expose rustc_trait_selection::error_reporting::ambiguity module 2024-04-05 18:39:37 +02:00
Urgau
524f3c9c44 Take the polarity into account in compute_applicable_impls 2024-04-05 18:39:37 +02:00
Guillaume Gomez
9cb517aede
Rollup merge of #123496 - lcnr:wf-ping, r=compiler-errors
ping on wf changes, remove fixme

extend core type system pings to `wf.rs`

r? `@compiler-errors`
2024-04-05 16:38:52 +02:00
Guillaume Gomez
cb6a1c8d45
Rollup merge of #122894 - compiler-errors:downgrade, r=lcnr
Move check for error in impl header outside of reporting

Fixes #121006

r? lcnr

test location kinda sucks, can move it if needed
2024-04-05 16:38:49 +02:00
lcnr
6db7ac6233 ping on wf changes, remove fixme 2024-04-05 15:09:48 +02:00
Jacob Pratt
e01d3e0824
Rollup merge of #123477 - lcnr:forced_ambig-no-ice, r=compiler-errors
do not ICE in `fn forced_ambiguity` if we get an error

see the comment. currently causing an ICE in typenum which we've been unable to minimize.

r? `@compiler-errors`
2024-04-04 21:16:58 -04:00
Jacob Pratt
58eb6e5803
Rollup merge of #123464 - fmease:rn-has-proj-to-has-aliases, r=compiler-errors
Cleanup: Rename `HAS_PROJECTIONS` to `HAS_ALIASES` etc.

The name of the bitflag `HAS_PROJECTIONS` and of its corresponding method `has_projections` is quite historical dating back to a time when projections were the only kind of alias type.

I think it's time to update it to clear up any potential confusion for newcomers and to reduce unnecessary friction during contributor onboarding.

r? types
2024-04-04 21:16:58 -04:00
Jacob Pratt
fcb0e9d07a
Rollup merge of #123363 - lcnr:normalizes-to-zero-to-inf, r=BoxyUwU
change `NormalizesTo` to fully structurally normalize

notes in https://hackmd.io/wZ016dE4QKGIhrOnHLlThQ

need to also update the dev-guide once this PR lands. in short, the setup is now as follows:

`normalizes-to` internally implements one step normalization, applying that normalization to the `goal.predicate.term` causes the projected term to get recursively normalized. With this `normalizes-to` normalizes until the projected term is rigid, meaning that we normalize as many steps necessary, but at least 1.

To handle rigid aliases, we add another candidate only if the 1 to inf step normalization failed. With this `normalizes-to` is now full structural normalization. We can now change `AliasRelate` to simply emit `normalizes-to` goals for the rhs and lhs.

This avoids the concerns from https://github.com/rust-lang/trait-system-refactor-initiative/issues/103 and generally feels cleaner
2024-04-04 21:16:56 -04:00
lcnr
9444ca354a do not ICE in forced ambiguity if we get an error 2024-04-05 00:04:38 +02:00
Michael Goulet
43dae69341 Check def id before calling match_projection_projections 2024-04-04 16:01:13 -04:00
bors
a4b11c8e60 Auto merge of #121394 - oli-obk:define_opaque_types, r=compiler-errors
some smaller DefiningOpaqueTypes::No -> Yes switches

r? `@compiler-errors`

These are some easy cases, so let's get them out of the way first.
I added tests exercising the specialization code paths that I believe weren't tested so far.

follow-up to https://github.com/rust-lang/rust/pull/117348
2024-04-04 17:42:07 +00:00
León Orell Valerian Liehr
6f17b7f0ab
Rename HAS_PROJECTIONS to HAS_ALIASES etc. 2024-04-04 19:26:17 +02:00
Oli Scherer
0183d92df0 Allow defining opaque types when checking const equality bounds 2024-04-04 15:43:02 +00:00
Oli Scherer
8e226e092e Add some regression tests for opaque types and const generics 2024-04-04 15:02:27 +00:00
lcnr
92b280ce81 normalizes-to change from '1' to '0 to inf' steps 2024-04-04 12:39:58 +02:00
Oli Scherer
2247aaf276 Use DefineOpaqueTypes::Yes where the new solver is unconditionally used already 2024-04-04 10:16:52 +00:00
Oli Scherer
82ceed2add Specialization can switch to DefineOpaqueTypes::Yes without having an effect.
The reason is that in specialization graph computation we use `DefiningAnchor::Error`, so there's no difference anyway. And in the other use cases, we

* already errored in the specialization_graph computation, or
* already errored in coherence, or
* are comparing opaque types with inference variables already, or
* there are no opaque types involved
2024-04-04 10:01:45 +00:00
Oli Scherer
b54d72264a Use DefineOpaqueTypes::Yes in diagnostics code 2024-04-04 10:01:44 +00:00
bors
4c6c629866 Auto merge of #115538 - lcnr:fn-def-wf, r=compiler-errors
check `FnDef` return type for WF

better version of #106807, fixes #84533 (mostly). It's not perfect given that we still ignore WF requirements involving bound regions but I wasn't able to quickly write an example, so even if theoretically exploitable, it should be far harder to trigger.

This is strictly more restrictive than checking the return type for WF as part of the builtin `FnDef: FnOnce` impl (#106807) and moving to this approach in the future will not break any code.

~~It also agrees with my theoretical view of how this should behave~~

r? types
2024-04-04 08:43:53 +00:00
lcnr
d99c775feb unconstrained NormalizesTo term for opaques 2024-04-04 07:47:22 +02:00
bors
43f4f2a3b1 Auto merge of #119820 - lcnr:leak-check-2, r=jackh726
instantiate higher ranked goals outside of candidate selection

This PR modifies `evaluate` to more eagerly instantiate higher-ranked goals, preventing the `leak_check` during candidate selection from detecting placeholder errors involving that binder.

For a general background regarding higher-ranked region solving and the leak check, see https://hackmd.io/qd9Wp03cQVy06yOLnro2Kg.

> The first is something called the **leak check**. You can think of it as a "quick and dirty" approximation for the region check, which will come later. The leak check detects some kinds of errors early, essentially deciding between "this set of outlives constraints are guaranteed to result in an error eventually" or "this set of outlives constraints may be solvable".

## The ideal future

We would like to end up with the following idealized design to handle universal binders:
```rust
fn enter_forall<'tcx, T, R>(
    forall: Binder<'tcx, T>,
    f: impl FnOnce(T) -> R,
) -> R {
    let new_universe = infcx.increment_universe_index();
    let value = instantiate_binder_with_placeholders_in(new_universe, forall);

    let result = f(value);

    eagerly_handle_higher_ranked_region_constraints_in(new_universe);
    infcx.decrement_universe_index();

    assert!(!result.has_placeholders_in_or_above(new_universe));
    result
}
```

That is, when universally instantiating a binder, anything using the placeholders has to happen inside of a limited scope (the closure `f`). After this closure has completed, all constraints involving placeholders are known.

We then handle any *external constraints* which name these placeholders. We destructure `TypeOutlives` constraints involving placeholders and eagerly handle any region constraints involving these placeholders. We do not return anything mentioning the placeholders created inside of this function to the caller.

Being able to eagerly handle *all* region constraints involving placeholders will be difficult due to complex `TypeOutlives` constraints, involving inference variables or alias types, and higher ranked implied bounds. The exact issues and possible solutions are out of scope of this FCP.

#### How does the leak check fit into this

The `leak_check` is an underapproximation of `eagerly_handle_higher_ranked_region_constraints_in`. It detects some kinds of errors involving placeholders from `new_universe`, but not all of them.

It only looks at region outlives constraints, ignoring `TypeOutlives`, and checks whether one of the following two conditions are met for **placeholders in or above `new_universe`**, in which case it results in an error:
- `'!p1: '!p2` a placeholder `'!p2` outlives a different placeholder `'!p1`
- `'!p1: '?2` an inference variable `'?2` outlives a placeholder `'!p1` *which it cannot name*

It does not handle all higher ranked region constraints, so we still return constraints involving placeholders from `new_universe` which are then (re)checked by `lexical_region_resolve` or MIR borrowck.

As we check higher ranked constraints in the full regionck anyways, the `leak_check` is not soundness critical. It's current only purpose is to move some higher ranked region errors earlier, enabling it to guide type inference and trait solving. Adding additional uses of the `leak_check` in the future would only strengthen inference and is therefore not breaking.

## Where do we use currently use the leak check

The `leak_check` is currently used in two places:

Coherence does not use a proper regionck, only relying on the `leak_check` called [at the end of the implicit negative overlap check](8b94152af6/compiler/rustc_trait_selection/src/traits/coherence.rs (L235-L238)). During coherence all parameters are instantiated with inference variables, so the only possible region errors are higher-ranked. We currently also sometimes make guesses when destructuring `TypeOutlives` constraints which can theoretically result in incorrect errors. This could result in overlapping impls.

We also use the `leak_check` [at the end of `fn evaluation_probe`](8b94152af6/compiler/rustc_trait_selection/src/traits/select/mod.rs (L607-L610)). This function is used during candidate assembly for `Trait` goals. Most notably we use [inside of `evaluate_candidate` during winnowing](0e4243538b/compiler/rustc_trait_selection/src/traits/select/mod.rs (L491-L502)). Conceptionally, it is as if we compute each candidate in a separate `enter_forall`.

## The current use in `fn evaluation_probe` is undesirable

Because we only instantiate a higher-ranked goal once inside of `fn evaluation_probe`, errors involving placeholders from that binder can impact selection. This results in inconsistent behavior ([playground](
*[playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=dac60ebdd517201788899ffa77364831)*)):

```rust
trait Leak<'a> {}
impl Leak<'_>      for Box<u32> {}
impl Leak<'static> for Box<u16> {}

fn impls_leak<T: for<'a> Leak<'a>>() {}

trait IndirectLeak<'a> {}
impl<'a, T: Leak<'a>> IndirectLeak<'a> for T {}
fn impls_indirect_leak<T: for<'a> IndirectLeak<'a>>() {}

fn main() {
    // ok
    //
    // The `Box<u16>` impls fails the leak check,
    // meaning that we apply the `Box<u32>` impl.
    impls_leak::<Box<_>>();

    // error: type annotations needed
    //
    // While the `Box<u16>` impl would fail the leak check
    // we have already instantiated the binder while applying
    // the generic `IndirectLeak` impl, so during candidate
    // selection of `Leak` we do not detect the placeholder error.
    // Evaluation of `Box<_>: Leak<'!a>` is therefore ambiguous,
    // resulting in `for<'a> Box<_>: Leak<'a>` also being ambiguous.
    impls_indirect_leak::<Box<_>>();
}
```

We generally prefer `where`-bounds over implementations during candidate selection, both for [trait goals](11f32b73e0/compiler/rustc_trait_selection/src/traits/select/mod.rs (L1863-L1887)) and during [normalization](11f32b73e0/compiler/rustc_trait_selection/src/traits/project.rs (L184-L198)). However, we currently **do not** use the `leak_check` during candidate assembly in normalizing. This can result in inconsistent behavior:
```rust
trait Trait<'a> {
    type Assoc;
}
impl<'a, T> Trait<'a> for T {
    type Assoc = usize;
}

fn trait_bound<T: for<'a> Trait<'a>>() {}
fn projection_bound<T: for<'a> Trait<'a, Assoc = usize>>() {}

// A function with a trivial where-bound which is more
// restrictive than the impl.
fn function<T: Trait<'static, Assoc = usize>>() {
    // ok
    //
    // Proving `for<'a> T: Trait<'a>` using the where-bound results
    // in a leak check failure, so we use the more general impl,
    // causing this to succeed.
    trait_bound::<T>();

    // error
    //
    // Proving the `Projection` goal `for<'a> T: Trait<'a, Assoc = usize>`
    // does not use the leak check when trying the where-bound, causing us
    // to prefer it over the impl, resulting in a placeholder error.
    projection_bound::<T>();

    // error
    //
    // Trying to normalize the type `for<'a> fn(<T as Trait<'a>>::Assoc)`
    // only gets to `<T as Trait<'a>>::Assoc` once `'a` has been already
    // instantiated, causing us to prefer the where-bound over the impl
    // resulting in a placeholder error. Even if were were to also use the
    // leak check during candidate selection for normalization, this
    // case would still not compile.
    let _higher_ranked_norm: for<'a> fn(<T as Trait<'a>>::Assoc) = |_| ();
}
```

This is also likely to be more performant. It enables more caching in the new trait solver by simply [recursively calling the canonical query][new solver] after instantiating the higher-ranked goal.

It is also unclear how to add the leak check to normalization in the new solver. To handle https://github.com/rust-lang/trait-system-refactor-initiative/issues/1 `Projection` goals are implemented via `AliasRelate`. This again means that we instantiate the binder before ever normalizing any alias. Even if we were to avoid this, we lose the ability to [cache normalization by itself, ignoring the expected `term`](5bd5d214ef/compiler/rustc_trait_selection/src/solve/normalizes_to/mod.rs (L34-L49)). We cannot replace the `term` with an inference variable before instantiating the binder, as otherwise `for<'a> T: Trait<Assoc<'a> = &'a ()>` breaks. If we only replace the term after instantiating the binder, we cannot easily evaluate the goal in a separate context, as [we'd then lose the information necessary for the leak check](11f32b73e0/compiler/rustc_next_trait_solver/src/canonicalizer.rs (L230-L232)). Adding this information to the canonical input also seems non-trivial.

## Proposed solution

I propose to instantiate the binder outside of candidate assembly, causing placeholders from higher-ranked goals to get ignored while selecting their candidate. This mostly[^1] matches the [current behavior of the new solver][new solver]. The impact of this change is therefore as follows:

```rust
trait Leak<'a> {}
impl Leak<'_>      for Box<u32> {}
impl Leak<'static> for Box<u16> {}

fn impls_leak<T: for<'a> Leak<'a>>() {}

trait IndirectLeak<'a> {}
impl<'a, T: Leak<'a>> IndirectLeak<'a> for T {}
fn impls_indirect_leak<T: for<'a> IndirectLeak<'a>>() {}

fn guide_selection() {
    // ok -> ambiguous
    impls_leak::<Box<_>>();

    // ambiguous
    impls_indirect_leak::<Box<_>>();
}

trait Trait<'a> {
    type Assoc;
}
impl<'a, T> Trait<'a> for T {
    type Assoc = usize;
}

fn trait_bound<T: for<'a> Trait<'a>>() {}
fn projection_bound<T: for<'a> Trait<'a, Assoc = usize>>() {}

// A function which a trivial where-bound which is more
// restrictive than the impl.
fn function<T: Trait<'static, Assoc = usize>>() {
    // ok -> error
    trait_bound::<T>();

    // error
    projection_bound::<T>();

    // error
    let _higher_ranked_norm: for<'a> fn(<T as Trait<'a>>::Assoc) = |_| ();
}
```

This does not change the behavior if candidates have higher ranked nested goals, as in this case the `leak_check` causes the nested goal to result in an error ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a74c25300b23db9022226de99d8a2fa6)):
```rust
trait LeakCheckFailure<'a> {}
impl LeakCheckFailure<'static> for () {}

trait Trait<T> {}
impl Trait<u32> for () where for<'a> (): LeakCheckFailure<'a> {}
impl Trait<u16> for () {}
fn impls_trait<T: Trait<U>, U>() {}
fn main() {
    // ok
    //
    // It does not matter whether candidate assembly
    // considers the placeholders from higher-ranked goal.
    //
    // Either `for<'a> (): LeakCheckFailure<'a>` has no
    // applicable candidate or it has a single applicable candidate
    // when then later results in an error. This allows us to
    // infer `U` to `u16`.
    impls_trait::<(), _>()
}
```

## Impact on existing crates

This is a **breaking change**. [A crater run](https://github.com/rust-lang/rust/pull/119820#issuecomment-1926862174) found 17 regressed crates with 7 root causes.

For a full analysis of all affected crates, see https://gist.github.com/lcnr/7c1c652f30567048ea240554a36ed95c.

---

I believe this breakage to be acceptable and would merge this change. I am confident that the new position of the leak check matches our idealized future and cannot envision any other consistent alternative. Where possible, I intend to open PRs fixing/avoiding the regressions before landing this PR.

I originally intended to remove the `coherence_leak_check` lint in the same PR. However, while I am confident in the *position* of the leak check, deciding on its exact behavior is left as future work, cc #112999. This PR therefore only moves the leak check while keeping the lint when relying on it in coherence.

[new solver]: https://github.com/rust-lang/rust/blob/master/compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs#L479-L484

[^1]: the new solver has a separate cause of inconsistent behavior rn https://github.com/rust-lang/trait-system-refactor-initiative/issues/53#issuecomment-1914310171

r? `@nikomatsakis`
2024-04-04 04:36:12 +00:00
bors
0accf4ec4c Auto merge of #123440 - jhpratt:rollup-yat6crk, r=jhpratt
Rollup of 4 pull requests

Successful merges:

 - #122356 (std::rand: fix dragonflybsd after #121942.)
 - #123093 (Add a nice header to our README.md)
 - #123307 (Fix f16 and f128 feature gating on different editions)
 - #123401 (Check `x86_64` size assertions on `aarch64`, too)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-04 02:11:23 +00:00
Boxy
82789763c7 rebase 2024-04-04 02:14:57 +01:00
lcnr
2b67f0104a check FnDef return type for WF 2024-04-04 01:55:29 +01:00
Jacob Pratt
4332498a6d
Rollup merge of #123401 - Zalathar:assert-size-aarch64, r=fmease
Check `x86_64` size assertions on `aarch64`, too

(Context: https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Checking.20size.20assertions.20on.20aarch64.3F)

Currently the compiler has around 30 sets of `static_assert_size!` for various size-critical data structures (e.g. various IR nodes), guarded by `#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]`.

(Presumably this cfg avoids having to maintain separate size values for 32-bit targets and unusual 64-bit targets. Apparently it may have been necessary before the i128/u128 alignment changes, too.)

This is slightly incovenient for people on aarch64 workstations (e.g. Macs), because the assertions normally aren't checked until we push to a PR. So this PR adds `aarch64` to the `#[cfg(..)]` guarding all of those assertions in the compiler.

---

Implemented with a simple find/replace. Verified by manually inspecting each `static_assert_size!` in `compiler/`, and checking that either the replacement succeeded, or adding aarch64 wouldn't have been appropriate.
2024-04-03 20:17:06 -04:00
bors
b4acbe4233 Auto merge of #123240 - compiler-errors:assert-args-compat, r=fmease
Assert that args are actually compatible with their generics, rather than just their count

Right now we just check that the number of args is right, rather than actually checking the kinds. Uplift a helper fn that I wrote from trait selection to do just that. Found a couple bugs along the way.

r? `@lcnr` or `@fmease` (or anyone really lol)
2024-04-04 00:09:02 +00:00
lcnr
4fa5fb684e move leak check out of candidate evaluation
this prevents higher ranked goals from guiding selection
2024-04-03 22:32:46 +01: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
Michael Goulet
c9f8529793 Uplift and start using check_args_compatible more liberally 2024-04-03 11:18:55 -04:00
Michael Goulet
e3025d6a55 Stop chopping off args for no reason 2024-04-03 11:16:58 -04:00
Zalathar
2d47cd77ac Check x86_64 size assertions on aarch64, too
This makes it easier for contributors on aarch64 workstations (e.g. Macs) to
notice when these assertions have been violated.
2024-04-03 16:53:03 +11:00
bors
b688d53a17 Auto merge of #123396 - jhpratt:rollup-oa54mh1, r=jhpratt
Rollup of 5 pull requests

Successful merges:

 - #122865 (Split hir ty lowerer's error reporting code in check functions to mod errors.)
 - #122935 (rename ptr::from_exposed_addr -> ptr::with_exposed_provenance)
 - #123182 (Avoid expanding to unstable internal method)
 - #123203 (Add `Context::ext`)
 - #123380 (Improve bootstrap comments)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-03 02:13:07 +00:00
Jacob Pratt
0697ee9af5
Rollup merge of #122865 - surechen:refactor_astconv_error_report_20240321, r=lcnr
Split hir ty lowerer's error reporting code in check functions to mod errors.

Move some error report codes to mod `astconv/errors.rs`

r? `@lcnr`
2024-04-02 20:37:39 -04:00
bors
40f743da23 Auto merge of #122791 - compiler-errors:make-coinductive-always, r=lcnr
Make inductive cycles always ambiguous

 This makes inductive cycles always result in ambiguity rather than be treated like a stack-dependent error.

This has some  interactions with specialization, and so breaks a few UI tests that I don't agree should've ever worked in the first place, and also breaks a handful of crates in a way that I don't believe is a problem.

On the bright side, it puts us in a better spot when it comes to eventually enabling coinduction everywhere.

## Results

This was cratered in https://github.com/rust-lang/rust/pull/116494#issuecomment-2008657494, which boils down to two regressions:
* `lu_packets` - This code should have never compiled in the first place. More below.
* **ALL** other regressions are due to `commit_verify@0.11.0-beta.1` (edit: and `commit_verify@0.10.x`) - This actually seems to be fixed in version `0.11.0-beta.5`, which is the *most* up to date version, but it's still prerelease on crates.io so I don't think cargo ends up picking `beta.5` when building dependent crates.

### `lu_packets`

Firstly, this crate uses specialization, so I think it's automatically worth breaking. However, I've minimized [the regression](https://crater-reports.s3.amazonaws.com/pr-116494-3/try%23d614ed876e31a5f3ad1d0fbf848fcdab3a29d1d8/gh/lcdr.lu_packets/log.txt) to:

```rust
// Upstream crate
pub trait Serialize {}
impl Serialize for &() {}
impl<S> Serialize for &[S] where for<'a> &'a S: Serialize {}

// ----------------------------------------------------------------------- //

// Downstream crate
#![feature(specialization)]
#![allow(incomplete_features, unused)]

use upstream::Serialize;

trait Replica {
    fn serialize();
}

impl<T> Replica for T {
    default fn serialize() {}
}

impl<T> Replica for Option<T>
where
    for<'a> &'a T: Serialize,
{
    fn serialize() {}
}
```

Specifically this fails when computing the specialization graph for the `downstream` crate.

The code ends up cycling on `&[?0]: Serialize` when we equate `&?0 = &[?1]` during impl matching, which ends up needing to prove `&[?1]: Serialize`, which since cycles are treated like ambiguity, ends up in a **fatal overflow**. For some reason this requires two crates, squashing them into one crate doesn't work.

Side-note: This code is subtly order dependent. When minimizing, I ended up having the code start failing on `nightly` very easily after removing and reordering impls. This seems to me all the more reason to remove this behavior altogether.

## Side-note: Item Bounds (edit: this was fixed independently in #121123)

Due to the changes in #120584 where we now consider an alias's item bounds *and* all the item bounds of the alias's nested self type aliases, I've had to add e6b64c6194 which is a hack to make sure we're not eagerly normalizing bounds that have nothing to do with the predicate we're trying to solve, and which result in.

This is fixed in a more principled way in #121123.

---

r? lcnr for an initial review
2024-04-03 00:09:44 +00:00
bors
5dbaafdb93 Auto merge of #123340 - fmease:rustdoc-simplify-auto-trait-impl-synth, r=GuillaumeGomez
rustdoc: heavily simplify the synthesis of auto trait impls

`gd --numstat HEAD~2 HEAD src/librustdoc/clean/auto_trait.rs`
**+315 -705** 🟩🟥🟥🟥

---

As outlined in issue #113015, there are currently 3[^1] large separate routines that “clean” `rustc_middle::ty` data types related to generics & predicates to rustdoc data types. Every single one has their own kinds of bugs. While I've patched a lot of bugs in each of the routines in the past, it's about time to unify them. This PR is only the first in a series. It completely **yanks** the custom “bounds cleaning” of mod `auto_trait` and reuses the routines found in mod `simplify`. As alluded to, `simplify` is also flawed but it's still more complete than `auto_trait`'s routines. [See also my review comment over at `tests/rustdoc/synthetic_auto/bounds.rs`](https://github.com/rust-lang/rust/pull/123340#discussion_r1546900539).

This is preparatory work for rewriting “bounds cleaning” from scratch in follow-up PRs in order to finally [fix] #113015.

Apart from that, I've eliminated all potential sources of *instability* in the rendered output.
See also #119597. I'm pretty sure this fixes #119597.

This PR does not attempt to fix [any other issues related to synthetic auto trait impls](https://github.com/rust-lang/rust/issues?q=is%3Aissue+is%3Aopen+label%3AA-synthetic-impls%20label%3AA-auto-traits).
However, it's definitely meant to be a *stepping stone* by making `auto_trait` more contributor-friendly.

---

* Replace `FxHash{Map,Set}` with `FxIndex{Map,Set}` to guarantee a stable iteration order
  * Or as a perf opt, `UnordSet` (a thin wrapper around `FxHashSet`) in cases where we never iterate over the set.
  * Yes, we do make use of `swap_remove` but that shouldn't matter since all the callers are deterministic. It does make the output less “predictable” but it's still better than before. Ofc, I rely on `rustc_infer` being deterministic. I hope that holds.
* Utilizing `clean::simplify` over the custom “bounds cleaning” routines wipes out the last reference to `collect_referenced_late_bound_regions` in rustdoc (`simplify` uses `bound_vars`) which was a source of instability / unpredictability (cc #116388)
* Remove the types `RegionTarget` and `RegionDeps` from `librustdoc`. They were duplicates of the identical types found in `rustc`. Just import them from `rustc`. For some reason, they were duplicated when splitting `auto_trait` in two in #49711.
* Get rid of the useless “type namespace” `AutoTraitFinder` in `librustdoc`
  * The struct only held a `DocContext`, it was over-engineered
  * Turn the associated functions into free ones
    * Eliminates rightward drift; increases legibility
  * `rustc` also contains a useless `AutoTraitFinder` struct but I plan on removing that in a follow-up PR
* Rename a bunch of methods to be way more descriptive
* Eliminate `use super::*;`
  * Lead to `clean/mod.rs` accumulating a lot of unnecessary imports
  * Made `auto_traits` less modular
* Eliminate a custom `TypeFolder`: We can just use the rustc helper `fold_regions` which does that for us

I plan on adding extensive documentation to `librustdoc`'s `auto_trait` in follow-up PRs.
I don't want to do that in this PR because further refactoring & bug fix PRs may alter the overall structure of `librustdoc`'s & `rustc`'s `auto_trait` modules to a great degree. I'm slowly digging into the dark details of `rustc`'s `auto_trait` module again and once I have the full picture I will be able to provide proper docs.

---

While this PR does indeed touch `rustc`'s `auto_trait` — mostly tiny refactorings — I argue this PR doesn't need any compiler reviewers next to rustdoc ones since that module falls under the purview of rustdoc — it used to be part of `librustdoc` after all (#49711).

Sorry for not having split this into more commits. If you'd like me to I can try to split it into more atomic commits retroactively. However, I don't know if that would actually make reviewing easier. I think the best way to review this might just be to place the master version of `auto_trait` on the left of your screen and the patched one on the right, not joking.

r? `@GuillaumeGomez`

[^1]: Or even 4 depending on the way you're counting.
2024-04-02 12:13:44 +00:00
surechen
1012218ba8 t plit astconv's error report code in check functions to mod errors.
Move some error report codes to mod `astconv/errors.rs`
2024-04-02 20:10:35 +08:00
Michael Goulet
09ea3f93ee Fix obligation param and bless tests 2024-04-01 22:48:23 -04:00
Michael Goulet
5f59b7f763 Instantiate closure-like bounds with placeholders to deal with binders correctly 2024-04-01 22:48:23 -04:00
León Orell Valerian Liehr
069e7f2a76
rustdoc: heavily simplify synthesis of auto trait impls 2024-04-02 01:49:57 +02:00
León Orell Valerian Liehr
cbd593ed18
rustdoc: synthetic impls: auto traits: Fx{Hash↦Index}{Map,Set} 2024-04-01 22:15:09 +02:00
Michael Goulet
88296bddf8 Remove EvaluatedToErrStackDependent 2024-03-31 20:44:30 -04:00
Michael Goulet
b8396d10c4 Always make inductive cycles as ambig during typeck 2024-03-31 20:44:30 -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
klensy
c64a440312 fix few more
warning: this argument is a mutable reference, but not used mutably
   --> compiler\rustc_trait_selection\src\traits\project.rs:511:12
    |
511 |     selcx: &mut SelectionContext<'a, 'tcx>,
    |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&SelectionContext<'a, '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_trait_selection\src\traits\specialize\specialization_graph.rs:201:28
    |
201 | fn iter_children(children: &mut Children) -> impl Iterator<Item = DefId> + '_ {
    |                            ^^^^^^^^^^^^^ help: consider changing to: `&Children`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut
2024-03-28 13:16:22 +03:00
klensy
bf47641726 compiler: fix unused_peekable clippy lint
warning: `peek` never called on `Peekable` iterator
   --> compiler\rustc_session\src\utils.rs:130:13
    |
130 |     let mut args = std::env::args_os().map(|arg| arg.to_string_lossy().to_string()).peekable();
    |             ^^^^
    |
    = help: consider removing the call to `peekable`
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unused_peekable

warning: `peek` never called on `Peekable` iterator
    --> compiler\rustc_trait_selection\src\traits\error_reporting\suggestions.rs:4934:17
     |
4934 |         let mut bounds = pred.bounds.iter().peekable();
     |                 ^^^^^^
     |
     = help: consider removing the call to `peekable`
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unused_peekable
2024-03-28 10:50:09 +03:00
Oli Scherer
727807293b Don't sort DefIds in suggestions 2024-03-27 14:02:16 +00:00
Oli Scherer
459ea32a27 Remove Partial/Ord from BoundRegion 2024-03-27 14:02:16 +00:00
Oli Scherer
e87d10846e Remove Ord from BoundTy 2024-03-27 14:02:16 +00:00
Oli Scherer
ae24fef028 Use TraitRef::to_string sorting in favor of TraitRef::ord, as the latter compares DefIds which we need to avoid 2024-03-27 14:02:15 +00:00
bors
dda2372cf3 Auto merge of #122802 - estebank:unconstrained-generic-const, r=Nadrieril
Provide structured suggestion for unconstrained generic constant

```
error: unconstrained generic constant
  --> $DIR/const-argument-if-length.rs:18:10
   |
LL |     pad: [u8; is_zst::<T>()],
   |          ^^^^^^^^^^^^^^^^^^^
   |
help: try adding a `where` bound
   |
LL | pub struct AtLeastByte<T: ?Sized> where [(); is_zst::<T>()]: {
   |                                   ++++++++++++++++++++++++++
```

Detect when the constant expression isn't `usize` and suggest casting:

```
error: unconstrained generic constant
 --> f300.rs:6:10
  |
6 |     bb::<{!N}>();
  |          ^^^^
-Ztrack-diagnostics: created at compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs:3539:36
  |
help: try adding a `where` bound
  |
5 | fn b<const N: bool>() where [(); {!N} as usize]: {
  |                       ++++++++++++++++++++++++++
```

Fix #122395.
2024-03-25 09:59:37 +00:00
Matthias Krüger
99e34b4f7a
Rollup merge of #122780 - GuillaumeGomez:rename-hir-local, r=oli-obk
Rename `hir::Local` into `hir::LetStmt`

Follow-up of #122776.

As discussed on [zulip](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Improve.20naming.20of.20.60ExprKind.3A.3ALet.60.3F).

I made this change into a separate PR because I'm less sure about this change as is. For example, we have `visit_local` and `LocalSource` items. Is it fine to keep these two as is (I supposed it is but I prefer to ask) or not? Having `Node::Local(LetStmt)` makes things more explicit but is it going too far?

r? ```@oli-obk```
2024-03-23 15:00:18 +01:00
bors
0ad5e0d2de Auto merge of #122900 - matthiaskrgr:rollup-nls90mb, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #114009 (compiler: allow transmute of ZST arrays with generics)
 - #122195 (Note that the caller chooses a type for type param)
 - #122651 (Suggest `_` for missing generic arguments in turbofish)
 - #122784 (Add `tag_for_variant` query)
 - #122839 (Split out `PredicatePolarity` from `ImplPolarity`)
 - #122873 (Merge my contributor emails into one using mailmap)
 - #122885 (Adjust better spastorino membership to triagebot's adhoc_groups)
 - #122888 (add a couple more tests)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-22 22:35:11 +00:00
Michael Goulet
5333f2a9d1 Move check for error in impl header outside of reporting 2024-03-22 17:46:40 -04:00
Guillaume Gomez
e0d3439226 Rename hir::Node::Local into hir::Node::LetStmt 2024-03-22 20:48:36 +01:00
Guillaume Gomez
b376f49e30 Rename hir::Local into hir::LetStmt 2024-03-22 20:36:21 +01:00
Michael Goulet
127e42d33b Use != Positive rather than == Negative
Feels more complete, and for ImplPolarity has the side-effect of making
sure we also handle reservation impls correctly
2024-03-22 11:16:57 -04:00
Michael Goulet
4b87c0b9c9 Split out ImplPolarity and PredicatePolarity 2024-03-22 11:16:56 -04:00
Michael Goulet
ff0c31e6b9 Programmatically convert some of the pat ctors 2024-03-22 11:13:29 -04:00
Michael Goulet
f0f224a37f Ty::new_ref and Ty::new_ptr stop using TypeAndMut 2024-03-22 11:13:27 -04:00
León Orell Valerian Liehr
b79335dbed
Update local variables and tracing calls
Most of the tracing calls didn't fully leverage the power of `tracing`.
For example, several of them used to hard-code method names / tracing spans
as well as variable names. Use `#[instrument]` and `?var` / `%var` (etc.) instead.

In my opinion, this is the proper way to migrate them from the old
AstConv nomenclature to the new HIR ty lowering one.
2024-03-22 06:32:23 +01:00
León Orell Valerian Liehr
82c2c8deb1
Update (doc) comments
Several (doc) comments were super outdated or didn't provide enough context.

Some doc comments shoved everything in a single paragraph without respecting
the fact that the first paragraph should be a single sentence because rustdoc
treats these as item descriptions / synopses on module pages.
2024-03-22 06:31:51 +01:00
León Orell Valerian Liehr
05d48b936f
Rename AstConv to HIR ty lowering
This includes updating astconv-related items and a few local variables.
2024-03-22 06:31:40 +01:00
Matthias Krüger
1757cb5871
Rollup merge of #122829 - ShoyuVanilla:gen-block-impl-fused-iter, r=compiler-errors
Implement `FusedIterator` for `gen` block

cc #117078
2024-03-22 01:07:31 +01:00
Shoyu Vanilla
ae4c5c891e Implement FusedIterator for gen block 2024-03-22 02:02:34 +09:00
Matthias Krüger
2e41425de6
Rollup merge of #122402 - weiznich:fix/122391, r=compiler-errors
Make `#[diagnostic::on_unimplemented]` format string parsing more robust

This commit fixes several issues with the format string parsing of the `#[diagnostic::on_unimplemented]` attribute that were pointed out by `@ehuss.`
In detail it fixes:

* Appearing format specifiers (display, etc). For these we generate a warning that the specifier is unsupported. Otherwise we ignore them
* Positional arguments. For these we generate a warning that positional arguments are unsupported in that location and replace them with the format string equivalent (so `{}` or `{n}` where n is the index of the positional argument)
* Broken format strings with enclosed }. For these we generate a warning about the broken format string and set the emitted message literally to the provided unformatted string
* Unknown format specifiers. For these we generate an additional warning about the unknown specifier. Otherwise we emit the literal string as message.

This essentially makes those strings behave like `format!` with the minor difference that we do not generate hard errors but only warnings. After that we continue trying to do something unsuprising (mostly either ignoring the broken parts or falling back to just giving back the literal string as provided).

Fix #122391

r? `@compiler-errors`
2024-03-21 17:46:48 +01:00
Matthias Krüger
e78522fd00
Rollup merge of #122358 - compiler-errors:bound-regions-in-generator, r=lcnr
Don't ICE when encountering bound regions in generator interior type

I'm pretty sure this meant to say "`has_free_regions`", probably just a typo in 4a4fc3bb5b. We can have bound regions (because we only convert non-bound regions into existential regions in generator interiors), but we can't have (non-ReErased) free regions.

r? lcnr
2024-03-21 12:05:05 +01:00
Georg Semmler
5568c569c0
Make #[diagnostic::on_unimplemented] format string parsing more robust
This commit fixes several issues with the format string parsing of the
`#[diagnostic::on_unimplemented]` attribute that were pointed out by
@ehuss.
In detail it fixes:

* Appearing format specifiers (display, etc). For these we generate a
warning that the specifier is unsupported. Otherwise we ignore them
* Positional arguments. For these we generate a warning that positional
arguments are unsupported in that location and replace them with the
format string equivalent (so `{}` or `{n}` where n is the index of the
positional argument)
* Broken format strings with enclosed }. For these we generate a warning
about the broken format string and set the emitted message literally to
the provided unformatted string
* Unknown format specifiers. For these we generate an additional warning
about the unknown specifier. Otherwise we emit the literal string as
message.

This essentially makes those strings behave like `format!` with the
minor difference that we do not generate hard errors but only warnings.
After that we continue trying to do something unsuprising (mostly either
ignoring the broken parts or falling back to just giving back the
literal string as provided).

Fix #122391
2024-03-21 08:27:26 +01:00
Esteban Küber
6b24fdf811 Provide structured suggestion for unconstrained generic constant
```
error: unconstrained generic constant
  --> $DIR/const-argument-if-length.rs:18:10
   |
LL |     pad: [u8; is_zst::<T>()],
   |          ^^^^^^^^^^^^^^^^^^^
   |
help: try adding a `where` bound
   |
LL | pub struct AtLeastByte<T: ?Sized> where [(); is_zst::<T>()]: {
   |                                   ++++++++++++++++++++++++++
```

Detect when the constant expression isn't `usize` and suggest casting:

```
error: unconstrained generic constant
 --> f300.rs:6:10
  |
6 |     bb::<{!N}>();
  |          ^^^^
-Ztrack-diagnostics: created at compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs:3539:36
  |
help: try adding a `where` bound
  |
5 | fn b<const N: bool>() where [(); {!N} as usize]: {
  |                       ++++++++++++++++++++++++++
```

Fix #122395.
2024-03-21 00:03:59 +00:00
Michael Goulet
aa39dbb962 Split item bounds and item super predicates 2024-03-20 13:00:34 -04:00
bors
a128516cf9 Auto merge of #122754 - Mark-Simulacrum:bootstrap-bump, r=albertlarsan68
Bump to 1.78 bootstrap compiler

https://forge.rust-lang.org/release/process.html#master-bootstrap-update-t-2-day-tuesday
2024-03-20 13:43:41 +00:00
Mark Rousskov
02f1930595 step cfgs 2024-03-20 08:49:13 -04:00
bors
c86f3ac24f Auto merge of #120717 - compiler-errors:cap-closure-kind, r=oli-obk
For async closures, cap closure kind, get rid of `by_mut_body`

Right now we have three `AsyncFn*` traits, and three corresponding futures that are returned by the `call_*` functions for them. This is fine, but it is a bit excessive, since the future returned by `AsyncFn` and `AsyncFnMut` are identical. Really, the only distinction we need to make with these bodies is "by ref" and "by move".

This PR removes `AsyncFn::CallFuture` and renames `AsyncFnMut::CallMutFuture` to `AsyncFnMut::CallRefFuture`. This simplifies MIR building for async closures, since we don't need to build an extra "by mut" body, but just a "by move" body which is materially different.

We need to do a bit of delicate handling of the ClosureKind for async closures, since we need to "cap" it to `AsyncFnMut` in some cases when we only care about what body we're looking for.

This also fixes a bug where `<{async closure} as Fn>::call` was returning a body that takes the async-closure receiver *by move*.

This also helps align the `AsyncFn` traits to the `LendingFn` traits' eventual designs.
2024-03-20 11:40:45 +00:00
Matthias Krüger
ffdb147aa4
Rollup merge of #122732 - compiler-errors:coroutine-captures-note, r=nnethercote
Remove redundant coroutine captures note

This note is redundant, since we'll always be printing this "captures the following types..." between *more* descriptive `BuiltinDerivedObligationCause`s.

Please review with whitespace disabled, since I also removed an unnecessary labeled break.
2024-03-20 05:51:23 +01:00
bors
b7dcabe55e Auto merge of #122119 - estebank:issue-117846, r=Nadrieril
Silence unecessary !Sized binding error

When gathering locals, we introduce a `Sized` obligation for each
binding in the pattern. *After* doing so, we typecheck the init
expression. If this has a type failure, we store `{type error}`, for
both the expression and the pattern. But later we store an inference
variable for the pattern.

We now avoid any override of an existing type on a hir node when they've
already been marked as `{type error}`, and on E0277, when it comes from
`VariableType` we silence the error in support of the type error.

Fix https://github.com/rust-lang/rust/issues/117846
2024-03-20 02:36:37 +00:00
Esteban Küber
b1575b71d4 Silence unecessary !Sized binding error
When gathering locals, we introduce a `Sized` obligation for each
binding in the pattern. *After* doing so, we typecheck the init
expression. If this has a type failure, we store `{type error}`, for
both the expression and the pattern. But later we store an inference
variable for the pattern.

We now avoid any override of an existing type on a hir node when they've
already been marked as `{type error}`, and on E0277, when it comes from
`VariableType` we silence the error in support of the type error.

Fix #117846.
2024-03-19 21:26:11 +00:00
Michael Goulet
05116c5c30 Only split by-ref/by-move futures for async closures 2024-03-19 16:59:23 -04:00
Michael Goulet
3d56178880 Remove redundant coroutine captures note 2024-03-19 12:02:21 -04:00
Michael Goulet
bca708b9fa Do binder folding eagerly in bound_coroutine_hidden_types
I refuse to fix this in the old solver; its lazy instantiation of
binders will be the end of me.
2024-03-19 11:52:45 -04:00
Michael Goulet
67f1c53c05 Don't ICE when encountering bound regions in generator interior type 2024-03-19 11:30:12 -04:00
bors
196ff446d2 Auto merge of #122493 - lukas-code:sized-constraint, r=lcnr
clean up `Sized` checking

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

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

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

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

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

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

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

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

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

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

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

## tuples are sized if the last type is sized

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

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

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

## `is_trivially_sized` for more types

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

I'm anticipating that this change will improve compile time for some real world programs.
2024-03-19 04:21:14 +00:00
bors
21d94a3d2c Auto merge of #122055 - compiler-errors:stabilize-atb, r=oli-obk
Stabilize associated type bounds (RFC 2289)

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

### What are we stabilizing?

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

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

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

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

### How does this differ from the RFC?

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

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

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

### Implementation history:

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

Closes #52662

[RFC 2289]: https://rust-lang.github.io/rfcs/2289-associated-type-bounds.html
2024-03-19 00:04:09 +00:00
Lukas Markeffsky
99efae342e address nits 2024-03-18 22:28:29 +01:00