Commit Graph

2434 Commits

Author SHA1 Message Date
bors 710ce90fbe Auto merge of #128250 - Amanieu:select_unpredictable, r=nikic
Add `select_unpredictable` to force LLVM to use CMOV

Since https://reviews.llvm.org/D118118, LLVM will no longer turn CMOVs into branches if it comes from a `select` marked with an `unpredictable` metadata attribute.

This PR introduces `core::intrinsics::select_unpredictable` which emits such a `select` and uses it in the implementation of `binary_search_by`.
2024-07-30 03:22:27 +00:00
Veera 3d5bd95558 Fix ICE Caused by Incorrectly Delaying E0107 2024-07-29 21:47:42 -04:00
Bryanskiy f2f9aab380 Delegation: support generics for delegation from free functions 2024-07-29 20:04:55 +03:00
Matthias Krüger 5551f54aa1
Rollup merge of #128174 - compiler-errors:trait-alias-marker, r=oli-obk
Don't record trait aliases as marker traits

Don't record `#[marker]` on trait aliases, since we use that to check for the (non-presence of) associated types and other things which don't make sense of trait aliases. We already enforce this attr is only applied to a trait.

Also do the same for `#[const_trait]`, which we also enforce is only applied to a trait. This is a drive-by change, but also worthwhile just in case.

Fixes #127222
2024-07-29 17:46:42 +02:00
Nicholas Nethercote 84ac80f192 Reformat `use` declarations.
The previous commit updated `rustfmt.toml` appropriately. This commit is
the outcome of running `x fmt --all` with the new formatting options.
2024-07-29 08:26:52 +10:00
Amanieu d'Antras 4f78f9fbb0 Force LLVM to use CMOV for binary search
Since https://reviews.llvm.org/D118118, LLVM will no longer turn CMOVs
into branches if it comes from a `select` marked with an `unpredictable`
metadata attribute.

This PR introduces `core::intrinsics::select_unpredictable` which emits
such a `select` and uses it in the implementation of `binary_search_by`.
2024-07-28 17:24:57 +01:00
Slanterns ec0b354092
stabilize `is_sorted` 2024-07-28 03:11:54 +08:00
bors 7c2012d0ec Auto merge of #121676 - Bryanskiy:polarity, r=petrochenkov
Support ?Trait bounds in supertraits and dyn Trait under a feature gate

This patch allows `maybe` polarity bounds under a feature gate. The only language change here is that corresponding hard errors are replaced by feature gates. Example:
```rust
#![feature(allow_maybe_polarity)]
...
trait Trait1 : ?Trait { ... } // ok
fn foo(_: Box<(dyn Trait2 + ?Trait)>) {} // ok
fn bar<T: ?Sized + ?Trait>(_: &T) {} // ok
```
Maybe bounds still don't do anything (except for `Sized` trait), however this patch will allow us to [experiment with default auto traits](https://github.com/rust-lang/rust/pull/120706#issuecomment-1934006762).

This is a part of the [MCP: Low level components for async drop](https://github.com/rust-lang/compiler-team/issues/727)
2024-07-26 20:14:16 +00:00
Bryanskiy fd9d0bfbac Forbid `?Trait` bounds repetitions 2024-07-26 16:35:05 +03:00
Trevor Gross ceae37188b
Rollup merge of #126575 - fmease:update-lint-type_alias_bounds, r=compiler-errors
Make it crystal clear what lint `type_alias_bounds` actually signifies

This is part of my work on https://github.com/rust-lang/rust/labels/F-lazy_type_alias ([tracking issue](#112792)).

---

To recap, the lint `type_alias_bounds` detects bounds on generic parameters and where clauses on (eager) type aliases. These bounds should've never been allowed because they are currently neither enforced[^1] at usage sites of type aliases nor thoroughly checked for correctness at definition sites due to the way type aliases are represented in the compiler. Allowing them was an oversight.

Explicitly label this as a known limitation of the type checker/system and establish the experimental feature `lazy_type_alias` as its eventual proper solution.

Where this becomes a bit tricky (for me as a rustc dev) are the "secondary effects" of these bounds whose existence I sadly can't deny. As a matter of fact, type alias bounds do play some small roles during type checking. However, after a lot of thinking over the last two weeks I've come to the conclusion (not without second-guessing myself though) that these use cases should not trump the fact that these bounds are currently *inherently broken*. Therefore the lint `type_alias_bounds` should and will continue to flag bounds that may have subordinate uses.

The two *known* secondary effects are:

1. They may enable the use of "shorthand" associated type paths `T::Assoc` (as opposed to fully qualified paths `<T as Trait>::Assoc`) where `T` is a type param bounded by some trait `Trait` which defines that assoc ty.
2. They may affect the default lifetime of trait object types passed as a type argument to the type alias. That concept is called (trait) object lifetime default.

The second one is negligible, no question asked. The first one however is actually "kinda nice" (for writability) and comes up in practice from time to time.

So why don't I just special-case trait bounds that "define" shorthand assoc type paths as originally planned in #125709?

1. Starting to permit even a tiny subset of bounds would already be enough to send a signal to users that bounds in type aliases have been legitimized and that they can expect to see type alias bounds in the wild from now on (proliferation). This would be actively misleading and dangerous because those bounds don't behave at all like one would expect, they are *not real*[^2]!
   1. Let's take `type A<T: Trait> = T::Proj;` for example. Everywhere else in the language `T: Trait` means `T: Trait + Sized`. For type aliases, that's not the case though: `T: Trait` and `T: Trait + ?Sized` for that matter do neither mean `T: Trait + Sized` nor `T: Trait + ?Sized` (for both!). Instead, whether `T` requires `Sized` or not entirely depends on the definition of `Trait`[^2]. Namely, whether or not it is bounded by `Sized`.
   2. Given `type A<T: Trait<AssocA = ()>> = T::AssocB;`, while `X: Trait` gets checked given `A<X>` (by virtue of projection wfchecking post alias expansion[^2]), the associated type constraint `AssocA = ()` gets dropped entirely! While we could choose to warn on such cases, it would inevitably lead to a huge pile of special cases.
   3. While it's common knowledge that the body / aliased type / RHS of an (eager) type alias does not get checked for well-formedness, I'm not sure if people would realize that that extends to bounds as well. Namely, `type A<T: Trait<[u8]>> = T::Proj;` compiles even if `Trait`'s generic parameter requires `Sized`. Of course, at usage sites `[u8]: Sized` would still end up getting checked[^2], so it's not a huge problem if you have full control over `A`. However, imagine that `A` was actually part of a public API and was never used inside the defining crate (not unreasonable). In such a scenario, downstream users would be presented with an impossible to use type alias! Remember, bounds may grow arbitrarily complex and nuanced in practice.
   4. Even if we allowed trait bounds that "define" shorthand assoc type paths, we would still need to continue to warn in cases where the assoc ty comes from a supertrait despite the fact that the shorthand syntax can be used: `type A<T: Sub> = T::Assoc;` does compile given `trait Sub: Super {}` and `trait Super { type Assoc; }`. However, `A<X>` does not enforce `X: Sub`, only `X: Super`[^2]. All that to say, type alias bounds are simply not real and we shouldn't pretend they are!
   5. Summarizing the points above, we would be legitimizing bounds that are completely broken!
2. It's infeasible to implement: Due to the lack of `TypeckResults` in `ItemCtxt` (and a way to propagate it to other parts of the compiler), the resolution of type-dependent paths in non-`Body` items (most notably type aliases) is not recoverable from the HIR alone which would be necessary because the information of whether an associated type path (projection) is a shorthand is only present pre&in-HIR and doesn't survive HIR ty lowering. Of course, I could rerun parts of HIR ty lowering inside the lint `type_alias_bounds` (namely, `probe_single_ty_param_bound_for_assoc_ty` which would need to be exposed or alternatively a stripped-down version of it). This likely has a performance impact and introduces complexity. In short, the "benefits" are not worth the costs.

---

* 3rd commit: Update a diagnostic to avoid suggesting type alias bounds
* 4th commit: Flag type alias bounds even if the RHS contains inherent associated types.
  * I started to allow them at some point in the past which was not correct (see commit for details)
* 5th commit: Allow type alias bounds if the RHS contains const projections and GCEs are enabled
  * (and add a `FIXME(generic_const_exprs)` to be revisited before (M)GCE's stabilization)
  * As a matter of fact type alias bounds are enforced in this case because the contained AnonConsts do get checked for well-formedness and crucially they inherit the generics and predicates of their parent item (here: the type alias)
* Remaining commits: Improve the lint `type_alias_bounds` itself

---

Fixes #125789 (sugg diag fix).
Fixes #125709 (wontfix, acknowledgement, sugg diag applic fix).
Fixes #104918 (sugg diag applic fix).
Fixes #100270 (wontfix, acknowledgement, sugg diag applic fix).
Fixes #94398 (true fix).

r? `@compiler-errors` `@oli-obk`

[^1]: From the perspective of the trait solver.
[^2]: Given `type A<T: Trait> = T::Proj;`, the reason why the trait bound "`T: Trait`" gets *seemingly* enforced at usage sites of the type alias `A` is simply because `A<X>` gets expanded to "`<X as Trait>::Proj`" very early on and it's the *expansion* that gets checked for well-formedness, not the type alias reference.
2024-07-26 02:20:28 -04:00
Matthias Krüger 29314e4fca
Rollup merge of #127220 - BoxyUwU:dropck_handle_extra_impl_params, r=compiler-errors
Graciously handle `Drop` impls introducing more generic parameters than the ADT

Follow up to #110577
Fixes #126378
Fixes #126889

## Motivation

A current issue with the way we check drop impls do not specialize any of their generic parameters is that when the `Drop` impl introduces *more* generic parameters than are present on the ADT, we fail to prove any bounds involving those parameters. This can be demonstrated with the following [code on stable](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=139b65e4294634d7286a3282bc61e628) which fails due to the fact that `<T as Trait>::Assoc == U` is not present in `Foo`s `ParamEnv` even though arguably there is no reason it cannot compiler:
```rust
struct Foo<T: Trait>(T);

trait Trait {
    type Assoc;
}

impl<T: Trait<Assoc = U>, U: ?Sized> Drop for Foo<T> {
    //~^ ERROR: `Drop` impl requires `<T as Trait>::Assoc == U` but the struct ...
    fn drop(&mut self) {}
}

fn main() {}
```

I think the motivation for supporting this code is somewhat lacking, it might be useful in practice for deeply nested associated types where you might want to be able to write:
`where T: Trait<Assoc: Other<AnotherAssoc: MoreTrait<YetAnotherAssoc: InnerTrait<Final = U>>>>`
in order to be able to just use `U` in the function body instead of writing out the whole nested associated type. Regardless I don't think there is really any reason to *not* support this code and it is relatively easy to support it.

What I find slightly more compelling is the fact that when defining a const parameter `const N: u8` we desugar that to having a where clause requiring the constant `N` is typed as `u8` (`ClauseKind::ConstArgHasType`). As we *always* desugar const parameters to have these bounds, if we attempt to prove that some const parameter `N` is of type `u8` and there is no bound on `N` in the enviroment that generally indicates usage of an incorrect `ParamEnv` (this has caught a bug already).

Given that, if we write the following code:
```rust
#![feature(associated_const_equality)]
struct Foo<T: Trait>(T);

trait Trait {
    const ASSOC: usize;
}

impl<T: Trait<ASSOC = N>, const N: usize> Drop for Foo<T> {
    fn drop(&mut self) {}
}

fn main() {}
```

The `Drop` impl would have this desugared where clause about `N` being of type `usize`, and if we were to try to prove that where clause in `Foo`'s `ParamEnv` we would ICE as there would not be any `ConstArgHasType` in the environment (which generally indicates improper `ParamEnv` usage. As this is otherwise well formed code (the `T: Trait<ASSOC = N>` causes `N` to be constrained) we have to handle this *somehow* and I believe the only principled way to support this is the changes I have made to `dropck.rs` that would cause these code examples to compiler (Perhaps we could just throw out all `ConstArgHasType` where clauses from the predicates we prove but that makes me nervous even if it might actually be okay).

## The changes

Currently the way `dropck.rs` works is that take the `ParamEnv` of the ADT and instantiate it with the generic arguments used on the self ty of the `impl`. We then instantiate the predicates of the drop impl with the identity params to the impl,  e.g. in the original example `<T as Trait>::Assoc == U` stays as `<T as Trait>::Assoc == U`. We then attempt to prove all the where clauses in the instantiated env of the self type ADT.

This PR changes us to first instantiate the impl with infer vars, then we equate the self type (with infer vars as its generic arguments) with the self type as written by the user. This causes all generic parameters on the impl that are constrained via associated type/const equality bounds to be left as inference variables while all other parameters are still `Ty`/`Const`/`Region`

Finally when instantiating the predicates on the impl, instead of using the identity arguments, we use the list of inference variables of which some have been inferred to the impl parameters. In practice this means that we wind up proving `<T as Trait>::Assoc == ?x` which can succeed just fine. In the const generics example we would wind up trying to prove `ConstArgHasType(?x: usize)` instead of `ConstArgHasType(N: usize)` which avoids the ICE as it is expected to encounter goals of the form `?x: usize`.

At a higher level the way I justify/think about this is that as we are proving goals in the environment of the ADT (`Foo` in the above examples), we do not expect to encounter generic parameters from a different environment so we must "deal with them" somehow. In this PR we handle them by replacing them with inference variables as they should either *actually* be unconstrained (and we will error later) or they are constrained to be equal to some associated type/const.

To go along with this it would be nice if we were not instantiating the adt's env with the generic arguments to the ADT in the `Drop` impl as it would make it clearer we are proving bounds in the adt's env instead of the `Drop` impl's. Instead we would map the predicates on the drop impl to be valid in the environment of the adt. In practice this causes diagnostic regressions as all of the generic parameters in errors refer to the ones defined on the adt; attempting to map these back to the ones on the impl, while possible, is involved as writing a `TypeFolder` over `FulfillmentError` is non trivial.

## Edge cases

There are some subtle interactions here:

One is that we should not allow `<T as Trait>::Assoc == U` to be present on the `Drop` if `U` is constrained by the self type of the impl and the bound is not present in the ADT's environment. demonstrated with the [following code](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=af839e2c3e43e03a624825c58af84dff):
```rust
trait Trait {
    type Assoc;
}

struct Foo<T: Trait, U: ?Sized>(T, U);

impl<T: Trait<Assoc = U>, U: ?Sized> Drop for Foo<T, U> {
    //~^ ERROR: `Drop` impl requires `<T as Trait>::Assoc == U`
    fn drop(&mut self) {}
}

fn main() {}
```
This is tested at `tests/ui/dropck/constrained_by_assoc_type_equality_and_self_ty.rs`.

Another weirdness is that we permit the following code to compile now:
```rust
struct Foo<T>(T);

impl<'a, T: 'a> Drop for Foo<T> {
    fn drop(&mut self) {}
}
```
This is caused by the fact that we permit unconstrained lifetime parameters in trait implementations as long as they are not used in associated types (so we do not wind up erroring on this code like we perhaps ought to), combined with the fact that as we are now proving `T: '?x` instead of `T: 'a` which allows proving the bound via `'?x= 'empty` wheras previously it would have failed.

This is tested as part of `tests/ui/dropck/reject-specialized-drops-8142.rs`.

---

r? `@compiler-errors`
2024-07-26 00:57:21 +02:00
Folkert be66415e11 use `ErrorGuaranteed` from emit 2024-07-25 20:12:14 +01:00
Amanieu d'Antras d4ca1ac8b9 rustfmt 2024-07-25 20:12:14 +01:00
Folkert de Vries c77b56901f Apply suggestions from code review
Co-authored-by: Amanieu d'Antras <amanieu@gmail.com>
2024-07-25 20:12:14 +01:00
Folkert 97738e1b86 apply fix suggested by lcnr 2024-07-25 20:12:14 +01:00
Amanieu d'Antras 4d747128eb Tweak type inference for `const` operands in inline asm
Previously these would be treated like integer literals and default to
`i32` if a type could not be determined. To allow for
forward-compatibility with `str` constants in the future, this PR
changes type inference to use an unbound type variable instead.

The actual type checking is deferred until after typeck where we still
ensure that the final type for the `const` operand is an integer type.
2024-07-25 20:12:14 +01:00
Bryanskiy 2a73553513 Support ?Trait bounds in supertraits and dyn Trait under a feature gate 2024-07-25 20:53:33 +03:00
Michael Goulet 12f1463b7e Don't record trait aliases as marker traits 2024-07-25 00:38:50 -04:00
León Orell Valerian Liehr 02a2f02727
Suggest full trait ref (with placeholders) on unresolved assoc tys 2024-07-23 01:26:25 +02:00
León Orell Valerian Liehr 3c8b108512
Inside eager ty aliases on unresolved assoc tys suggest fully qualifying instead of restricting their self ty 2024-07-23 01:26:24 +02:00
León Orell Valerian Liehr 898448ca58
HIR ty lowering: Refactor the way the projectee ("QSelf") gets passed to diagnostics 2024-07-23 01:23:54 +02:00
León Orell Valerian Liehr ef121f28d8
Suggesting an available assoc item is always maybe-incorrect 2024-07-23 01:18:18 +02:00
Esteban Küber 921de9d8ea Revert suggestion verbosity change 2024-07-22 22:51:53 +00:00
Esteban Küber b30fdec5fb On generic and lifetime removal suggestion, do not leave behind stray `,` 2024-07-22 22:04:49 +00:00
Esteban Küber 5c2b36a21c Change suggestion message wording 2024-07-22 22:04:49 +00:00
Esteban Küber c807ac0340 Use verbose suggestion for "wrong # of generics" 2024-07-22 22:04:49 +00:00
bors 20f23abbec Auto merge of #128041 - compiler-errors:uplift-errors-into-trait-sel, r=lcnr
Uplift most type-system related error reporting from `rustc_infer` to `rustc_trait_selection`

Completes the major part of #127492. The only cleanup that's needed afterwards is to actually use normalization in favor of the callback where needed, and deleting `can_eq_shallow`.

r? lcnr

Sorry for the large diff! Would prefer if comments can be handled in a follow-up (unless they're absolutely dealbreakers) because it seems bitrotty to let this sit.
2024-07-22 15:06:18 +00:00
Michael Goulet ce8a625092 Move all error reporting into rustc_trait_selection 2024-07-21 22:34:35 -04:00
Michael Goulet 5accaf3af4 Make type_var_origin take a vid 2024-07-21 22:33:15 -04:00
Jubilee 2ef7699a1a
Rollup merge of #128020 - compiler-errors:nlb-no-const, r=BoxyUwU
Just totally fully deny late-bound consts

Kinda don't care about supporting this until we have where clauses on binders. They're super busted and should be reworked in due time, and they are approximately 100% useless until then 😸

Fixes #127970
Fixes #127009

r? ``@BoxyUwU``
2024-07-21 17:44:29 -07:00
bors 9629b90b3f Auto merge of #127722 - BoxyUwU:new_adt_const_params_limitations, r=compiler-errors
Forbid borrows and unsized types from being used as the type of a const generic under `adt_const_params`

Fixes #112219
Fixes #112124
Fixes #112125

### Motivation

Currently the `adt_const_params` feature allows writing `Foo<const N: [u8]>` this is entirely useless as it is not possible to write an expression which evaluates to a type that is not `Sized`. In order to actually use unsized types in const generics they are typically written as `const N: &[u8]` which *is* possible to provide a value of.

Unfortunately allowing the types of const parameters to contain references is non trivial (#120961) as it introduces a number of difficult questions about how equality of references in the type system should behave. References in the types of const generics is largely only useful for using unsized types in const generics.

This PR introduces a new feature gate `unsized_const_parameters` and moves support for `const N: [u8]` and `const N: &...` from `adt_const_params` into it. The goal here hopefully is to experiment with allowing `const N: [u8]` to work without references and then eventually completely forbid references in const generics.

Splitting this out into a new feature gate means that stabilization of `adt_const_params` does not have to resolve #120961 which is the only remaining "big" blocker for the feature. Remaining issues after this are a few ICEs and naming bikeshed for `ConstParamTy`.

### Implementation

The implementation is slightly subtle here as we would like to ensure that a stabilization of `adt_const_params` is forwards compatible with any outcome of `unsized_const_parameters`. This is inherently tricky as we do not support unstable trait implementations and we determine whether a type is valid as the type of a const parameter via a trait bound.

There are a few constraints here:
- We would like to *allow for the possibility* of adding a `Sized` supertrait to `ConstParamTy` in the event that we wind up opting to not support unsized types and instead requiring people to write the 'sized version', e.g. `const N: [u8; M]` instead of `const N: [u8]`.
- Crates should be able to enable `unsized_const_parameters` and write trait implementations of `ConstParamTy` for `!Sized` types without downstream crates that only enable `adt_const_params` being able to observe this (required for std to be able to `impl<T> ConstParamTy for [T]`

Ultimately the way this is accomplished is via having two traits (sad), `ConstParamTy` and `UnsizedConstParamTy`. Depending on whether `unsized_const_parameters` is enabled or not we change which trait is used to check whether a type is allowed to be a const parameter.

Long term (when stabilizing `UnsizedConstParamTy`) it should be possible to completely merge these traits (and derive macros), only having a single `trait ConstParamTy` and `macro ConstParamTy`.

Under `adt_const_params` it is now illegal to directly refer to `ConstParamTy` it is only used as an internal impl detail by `derive(ConstParamTy)` and checking const parameters are well formed. This is necessary in order to ensure forwards compatibility with all possible future directions for `feature(unsized_const_parameters)`.

Generally the intuition here should be that `ConstParamTy` is the stable trait that everything uses, and `UnsizedConstParamTy` is that plus unstable implementations (well, I suppose `ConstParamTy` isn't stable yet :P).
2024-07-21 05:36:21 +00:00
Michael Goulet 3862095bd2 Just totally fully deny late-bound consts 2024-07-20 19:45:24 -04:00
bors 73a228116a Auto merge of #127658 - compiler-errors:precise-capturing-rustdoc-cross, r=fmease
Add cross-crate precise capturing support to rustdoc

Follow-up to #127632. Fixes #127228.

r? `@fmease`

Tracking:
* https://github.com/rust-lang/rust/issues/123432
2024-07-20 11:03:35 +00:00
Matthias Krüger cd8c5f78ec
Rollup merge of #127980 - nyurik:compiler-refs, r=oli-obk
Avoid ref when using format! in compiler

Clean up a few minor refs in `format!` macro, as it has a performance cost. Apparently the compiler is unable to inline `format!("{}", &variable)`, and does a run-time double-reference instead (format macro already does one level referencing).  Inlining format args prevents accidental `&` misuse.

See also https://github.com/rust-lang/rust-clippy/issues/10851
2024-07-20 07:13:45 +02:00
Yuri Astrakhan aef0e346de Avoid ref when using format! in compiler
Clean up a few minor refs in `format!` macro, as it has a performance cost. Apparently the compiler is unable to inline `format!("{}", &variable)`, and does a run-time double-reference instead (format macro already does one level referencing).  Inlining format args prevents accidental `&` misuse.
2024-07-19 14:52:07 -04:00
Matthias Krüger 115b086850
Rollup merge of #127976 - fmease:lta-cyclic-bivariant-param-better-err, r=compiler-errors
Lazy type aliases: Diagostics: Detect bivariant ty params that are only used recursively

Follow-up to errs's #127871. Extends the logic to cover LTAs, too, not just ADTs.
This change only takes effect with the next-gen solver enabled as cycle errors like
the one we have here are fatal in the old solver. That's my explanation anyways.

r? compiler-errors
2024-07-19 20:03:58 +02:00
Matthias Krüger a2c99cf87c
Rollup merge of #127966 - oli-obk:structured_diag, r=compiler-errors
Use structured suggestions for unconstrained generic parameters on impl blocks

I did not deduplicate with `UnusedGenericParameter`, because in contrast to type declarations, just using a generic parameter in an impl isn't enough, it must be used with the right variance and not just as part of a projection.
2024-07-19 20:03:57 +02:00
Matthias Krüger 3b20150b48
Rollup merge of #127814 - folkertdev:c-cmse-nonsecure-call-error-messages, r=oli-obk
`C-cmse-nonsecure-call`: improved error messages

tracking issue: #81391
issue for the error messages (partially implemented by this PR): #81347
related, in that it also deals with CMSE: https://github.com/rust-lang/rust/pull/127766

When using the `C-cmse-nonsecure-call` ABI, both the arguments and return value must be passed via registers. Previously, when violating this constraint, an ugly LLVM error would be shown. Now, the rust compiler itself will print a pretty message and link to more information.
2024-07-19 20:03:56 +02:00
León Orell Valerian Liehr 756459ed85
LTA: Diag: Detect bivariant ty params that are only used recursively 2024-07-19 18:53:40 +02:00
Oli Scherer a0db06bdeb Use structured suggestions for unconstrained generic parameters on impl blocks 2024-07-19 14:21:56 +00:00
bors 11e57241f1 Auto merge of #127956 - tgross35:rollup-8ten7pk, r=tgross35
Rollup of 7 pull requests

Successful merges:

 - #121533 (Handle .init_array link_section specially on wasm)
 - #127825 (Migrate `macos-fat-archive`, `manual-link` and `archive-duplicate-names` `run-make` tests to rmake)
 - #127891 (Tweak suggestions when using incorrect type of enum literal)
 - #127902 (`collect_tokens_trailing_token` cleanups)
 - #127928 (Migrate `lto-smoke-c` and `link-path-order` `run-make` tests to rmake)
 - #127935 (Change `binary_asm_labels` to only fire on x86 and x86_64)
 - #127953 ([compiletest] Search *.a when getting dynamic libraries on AIX)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-19 11:08:02 +00:00
bors 8c3a94a1c7 Auto merge of #125915 - camelid:const-arg-refactor, r=BoxyUwU
Represent type-level consts with new-and-improved `hir::ConstArg`

### Summary

This is a step toward `min_generic_const_exprs`. We now represent all const
generic arguments using an enum that differentiates between const *paths*
(temporarily just bare const params) and arbitrary anon consts that may perform
computations. This will enable us to cleanly implement the `min_generic_const_args`
plan of allowing the use of generics in paths used as const args, while
disallowing their use in arbitrary anon consts. Here is a summary of the salient
aspects of this change:

- Add `current_def_id_parent` to `LoweringContext`

  This is needed to track anon const parents properly once we implement
  `ConstArgKind::Path` (which requires moving anon const def-creation
  outside of `DefCollector`).

- Create `hir::ConstArgKind` enum with `Path` and `Anon` variants. Use it in the
  existing `hir::ConstArg` struct, replacing the previous `hir::AnonConst` field.

- Use `ConstArg` for all instances of const args. Specifically, use it instead
  of `AnonConst` for assoc item constraints, array lengths, and const param
  defaults.

- Some `ast::AnonConst`s now have their `DefId`s created in
  rustc_ast_lowering rather than `DefCollector`. This is because in some
  cases they will end up becoming a `ConstArgKind::Path` instead, which
  has no `DefId`. We have to solve this in a hacky way where we guess
  whether the `AnonConst` could end up as a path const since we can't
  know for sure until after name resolution (`N` could refer to a free
  const or a nullary struct). If it has no chance as being a const
  param, then we create a `DefId` in `DefCollector` -- otherwise we
  decide during ast_lowering. This will have to be updated once all path
  consts use `ConstArgKind::Path`.

- We explicitly use `ConstArgHasType` for array lengths, rather than
  implicitly relying on anon const type feeding -- this is due to the
  addition of `ConstArgKind::Path`.

- Some tests have their outputs changed, but the changes are for the
  most part minor (including removing duplicate or almost-duplicate
  errors). One test now ICEs, but it is for an incomplete, unstable
  feature and is now tracked at https://github.com/rust-lang/rust/issues/127009.

### Followup items post-merge

- Use `ConstArgKind::Path` for all const paths, not just const params.
- Fix (no github dont close this issue) #127009
- If a path in generic args doesn't resolve as a type, try to resolve as a const
  instead (do this in rustc_resolve). Then remove the special-casing from
  `rustc_ast_lowering`, so that all params will automatically be lowered as
  `ConstArgKind::Path`.
- (?) Consider making `const_evaluatable_unchecked` a hard error, or at least
  trying it in crater

r? `@BoxyUwU`
2024-07-19 08:44:51 +00:00
Trevor Gross fc6e34f38f
Rollup merge of #127891 - estebank:enum-type-sugg, r=estebank
Tweak suggestions when using incorrect type of enum literal

More accurate suggestions when writing wrong style of enum variant literal:

```
error[E0533]: expected value, found struct variant `E::Empty3`
  --> $DIR/empty-struct-braces-expr.rs:18:14
   |
LL |     let e3 = E::Empty3;
   |              ^^^^^^^^^ not a value
   |
help: you might have meant to create a new value of the struct
   |
LL |     let e3 = E::Empty3 {};
   |                        ++
```
```
error[E0533]: expected value, found struct variant `E::V`
  --> $DIR/struct-literal-variant-in-if.rs:10:13
   |
LL |     if x == E::V { field } {}
   |             ^^^^ not a value
   |
help: you might have meant to create a new value of the struct
   |
LL |     if x == (E::V { field }) {}
   |             +              +
```
```
error[E0618]: expected function, found enum variant `Enum::Unit`
  --> $DIR/suggestion-highlights.rs:15:5
   |
LL |     Unit,
   |     ---- enum variant `Enum::Unit` defined here
...
LL |     Enum::Unit();
   |     ^^^^^^^^^^--
   |     |
   |     call expression requires function
   |
help: `Enum::Unit` is a unit enum variant, and does not take parentheses to be constructed
   |
LL -     Enum::Unit();
LL +     Enum::Unit;
   |
```
```
error[E0599]: no variant or associated item named `tuple` found for enum `Enum` in the current scope
  --> $DIR/suggestion-highlights.rs:36:11
   |
LL | enum Enum {
   | --------- variant or associated item `tuple` not found for this enum
...
LL |     Enum::tuple;
   |           ^^^^^ variant or associated item not found in `Enum`
   |
help: there is a variant with a similar name
   |
LL |     Enum::Tuple(/* i32 */);
   |           ~~~~~~~~~~~~~~~~;
   |
```

Tweak "field not found" suggestion when giving struct literal for tuple struct type:

```
error[E0560]: struct `S` has no field named `x`
  --> $DIR/nested-non-tuple-tuple-struct.rs:8:19
   |
LL | pub struct S(f32, f32);
   |            - `S` defined here
...
LL |     let _x = (S { x: 1.0, y: 2.0 }, S { x: 3.0, y: 4.0 });
   |                   ^ field does not exist
   |
help: `S` is a tuple struct, use the appropriate syntax
   |
LL |     let _x = (S(/* f32 */, /* f32 */), S { x: 3.0, y: 4.0 });
   |               ~~~~~~~~~~~~~~~~~~~~~~~
2024-07-19 03:27:48 -05:00
Trevor Gross 986d6bf9fb
Rollup merge of #121533 - ratmice:wasm_init_fini_array, r=nnethercote
Handle .init_array link_section specially on wasm

Given that wasm-ld now has support for [.init_array](8f2bd8ae68/llvm/lib/MC/WasmObjectWriter.cpp (L1852)), it appears we can easily implement that section by falling through to the normal path rather than taking the typical custom_section path for wasm.

The wasm-ld appears to have a bunch of limitations. Only one static with the `link_section` in a crate or else you hit the fatal error in the link above "only one .init_array section fragment supported". They do not get merged.

You can still call multiple constructors by setting it to an array.

```
unsafe extern "C" fn ctor() {
    println!("foo");
}
#[used]
#[link_section = ".init_array"]
static FOO: [unsafe extern "C" fn(); 2] = [ctor, ctor];
```

Another issue appears to be that if crate *A* depends on crate *B*, but *A* doesn't call any symbols from *B* and *B* doesn't `#[export_name = ...]` any symbols, then crate *B*'s constructor will not be called.  The workaround to this is to provide an exported symbol in crate *B*.
2024-07-19 03:27:46 -05:00
Matthias Krüger d1250bc1d5
Rollup merge of #127929 - estebank:addr_of, r=compiler-errors
Use more accurate span for `addr_of!` suggestion

Use a multipart suggestion instead of a single whole-span replacement:

```
error[E0796]: creating a shared reference to a mutable static
  --> $DIR/reference-to-mut-static-unsafe-fn.rs:10:18
   |
LL |         let _y = &X;
   |                  ^^ shared reference to mutable static
   |
   = note: this shared reference has lifetime `'static`, but if the static ever gets mutated, or a mutable reference is created, then any further use of this shared reference is Undefined Behavior
help: use `addr_of!` instead to create a raw pointer
   |
LL |         let _y = addr_of!(X);
   |                  ~~~~~~~~~ +
```
2024-07-18 23:05:24 +02:00
Matthias Krüger 65de5d0472
Rollup merge of #127871 - compiler-errors:recursive, r=estebank
Mention that type parameters are used recursively on bivariance error

Right now when a type parameter is used recursively, even with indirection (so it has a finite size) we say that the type parameter is unused:

```
struct B<T>(Box<B<T>>);
```

This is confusing, because the type parameter is *used*, it just doesn't have its variance constrained. This PR tweaks that message to mention that it must be used *non-recursively*.

Not sure if we should actually mention "variance" here, but also I'd somewhat prefer we don't keep the power users in the dark w.r.t the real underlying issue, which is that the variance isn't constrained. That technical detail is reserved for a note, though.

cc `@fee1-dead`

Fixes #118976
Fixes #26283
Fixes #53191
Fixes #105740
Fixes #110466
2024-07-18 23:05:22 +02:00
Esteban Küber abf92c049d Use more accurate span for `addr_of!` suggestion
Use a multipart suggestion instead of a single whole-span replacement:

```
error[E0796]: creating a shared reference to a mutable static
  --> $DIR/reference-to-mut-static-unsafe-fn.rs:10:18
   |
LL |         let _y = &X;
   |                  ^^ shared reference to mutable static
   |
   = note: this shared reference has lifetime `'static`, but if the static ever gets mutated, or a mutable reference is created, then any further use of this shared reference is Undefined Behavior
help: use `addr_of!` instead to create a raw pointer
   |
LL |         let _y = addr_of!(X);
   |                  ~~~~~~~~~ +
```
2024-07-18 18:39:20 +00:00
Esteban Küber ec7a188f16 More accurate suggestions when writing wrong style of enum variant literal
```
error[E0533]: expected value, found struct variant `E::Empty3`
  --> $DIR/empty-struct-braces-expr.rs:18:14
   |
LL |     let e3 = E::Empty3;
   |              ^^^^^^^^^ not a value
   |
help: you might have meant to create a new value of the struct
   |
LL |     let e3 = E::Empty3 {};
   |                        ++
```
```
error[E0533]: expected value, found struct variant `E::V`
  --> $DIR/struct-literal-variant-in-if.rs:10:13
   |
LL |     if x == E::V { field } {}
   |             ^^^^ not a value
   |
help: you might have meant to create a new value of the struct
   |
LL |     if x == (E::V { field }) {}
   |             +              +
```
```
error[E0618]: expected function, found enum variant `Enum::Unit`
  --> $DIR/suggestion-highlights.rs:15:5
   |
LL |     Unit,
   |     ---- enum variant `Enum::Unit` defined here
...
LL |     Enum::Unit();
   |     ^^^^^^^^^^--
   |     |
   |     call expression requires function
   |
help: `Enum::Unit` is a unit enum variant, and does not take parentheses to be constructed
   |
LL -     Enum::Unit();
LL +     Enum::Unit;
   |
```
```
error[E0599]: no variant or associated item named `tuple` found for enum `Enum` in the current scope
  --> $DIR/suggestion-highlights.rs:36:11
   |
LL | enum Enum {
   | --------- variant or associated item `tuple` not found for this enum
...
LL |     Enum::tuple;
   |           ^^^^^ variant or associated item not found in `Enum`
   |
help: there is a variant with a similar name
   |
LL |     Enum::Tuple(/* i32 */);
   |           ~~~~~~~~~~~~~~~~;
   |
```
2024-07-18 18:20:35 +00:00
Folkert c2894a4297
improve error reporting 2024-07-18 14:32:10 +02:00
Folkert 6b6b8422ba
remove cmse validation from rustc_codegen_ssa
it was moved to hir_analysis in the previous commit
2024-07-18 12:42:43 +02:00
Folkert 7b63734961
move CMSE validation to hir_analysis 2024-07-18 12:42:40 +02:00
Matthias Krüger d78be31a2a
Rollup merge of #127888 - estebank:type-param-sugg, r=compiler-errors
More accurate span for type parameter suggestion

After:

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/impl-block-params-declared-in-wrong-spot-issue-113073.rs:3:10
   |
LL | impl Foo<T: Default> for String {}
   |          ^^^^^^^^^^ associated item constraint not allowed here
   |
help: declare the type parameter right after the `impl` keyword
   |
LL - impl Foo<T: Default> for String {}
LL + impl<T: Default> Foo<T> for String {}
   |
```

Before:

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/impl-block-params-declared-in-wrong-spot-issue-113073.rs:3:10
   |
LL | impl Foo<T: Default> for String {}
   |          ^^^^^^^^^^ associated item constraint not allowed here
   |
help: declare the type parameter right after the `impl` keyword
   |
LL | impl<T: Default> Foo<T> for String {}
   |     ++++++++++++     ~
```
2024-07-18 08:09:02 +02:00
Matthias Krüger a13d7dbecf
Rollup merge of #127878 - estebank:assoc-item-removal, r=fmease
Fix associated item removal suggestion

We were previously telling people to write what was already there, instead of removal (treating it as a `help`). We now properly suggest to remove the code that needs to be removed.

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/E0229.rs:13:25
   |
LL | fn baz<I>(x: &<I as Foo<A = Bar>>::A) {}
   |                         ^^^^^^^ associated item constraint not allowed here
   |
help: consider removing this associated item binding
   |
LL - fn baz<I>(x: &<I as Foo<A = Bar>>::A) {}
LL + fn baz<I>(x: &<I as Foo>::A) {}
   |
```
2024-07-18 08:09:01 +02:00
Noah Lev c8457e60e8 Remove some unintended changes to imports 2024-07-17 20:31:37 -07:00
Michael Goulet c02d0de871 Account for structs that have unused params in nested types in fields 2024-07-17 21:12:12 -04:00
Esteban Küber be9d961884 More accurate span for type parameter suggestion
After:

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/impl-block-params-declared-in-wrong-spot-issue-113073.rs:3:10
   |
LL | impl Foo<T: Default> for String {}
   |          ^^^^^^^^^^ associated item constraint not allowed here
   |
help: declare the type parameter right after the `impl` keyword
   |
LL - impl Foo<T: Default> for String {}
LL + impl<T: Default> Foo<T> for String {}
   |
```

Before:

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/impl-block-params-declared-in-wrong-spot-issue-113073.rs:3:10
   |
LL | impl Foo<T: Default> for String {}
   |          ^^^^^^^^^^ associated item constraint not allowed here
   |
help: declare the type parameter right after the `impl` keyword
   |
LL | impl<T: Default> Foo<T> for String {}
   |     ++++++++++++     ~
```
2024-07-18 00:10:48 +00:00
Esteban Küber e38032fb3a Fix associated item removal suggestion
We were previously telling people to write what was already there, instead of removal.

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/E0229.rs:13:25
   |
LL | fn baz<I>(x: &<I as Foo<A = Bar>>::A) {}
   |                         ^^^^^^^ associated item constraint not allowed here
   |
help: consider removing this associated item binding
   |
LL - fn baz<I>(x: &<I as Foo<A = Bar>>::A) {}
LL + fn baz<I>(x: &<I as Foo>::A) {}
   |
```
2024-07-17 21:30:40 +00:00
Michael Goulet a0a251a688 Account for self ty alias 2024-07-17 16:48:17 -04:00
Michael Goulet 3716a3fd31 Mention that type parameters are used recursively 2024-07-17 15:57:38 -04:00
Michael Goulet da2054f389 Add cross-crate precise capturing support to rustdoc 2024-07-17 11:06:10 -04:00
Boxy d0c11bf6e3 Split part of `adt_const_params` into `unsized_const_params` 2024-07-17 11:01:29 +01:00
Boxy 42cc42b942 Forbid `!Sized` types and references 2024-07-17 11:01:29 +01:00
Noah Lev 37ed7a4438 Add `ConstArgKind::Path` and make `ConstArg` its own HIR node
This is a very large commit since a lot needs to be changed in order to
make the tests pass. The salient changes are:

- `ConstArgKind` gets a new `Path` variant, and all const params are now
  represented using it. Non-param paths still use `ConstArgKind::Anon`
  to prevent this change from getting too large, but they will soon use
  the `Path` variant too.

- `ConstArg` gets a distinct `hir_id` field and its own variant in
  `hir::Node`. This affected many parts of the compiler that expected
  the parent of an `AnonConst` to be the containing context (e.g., an
  array repeat expression). They have been changed to check the
  "grandparent" where necessary.

- Some `ast::AnonConst`s now have their `DefId`s created in
  rustc_ast_lowering rather than `DefCollector`. This is because in some
  cases they will end up becoming a `ConstArgKind::Path` instead, which
  has no `DefId`. We have to solve this in a hacky way where we guess
  whether the `AnonConst` could end up as a path const since we can't
  know for sure until after name resolution (`N` could refer to a free
  const or a nullary struct). If it has no chance as being a const
  param, then we create a `DefId` in `DefCollector` -- otherwise we
  decide during ast_lowering. This will have to be updated once all path
  consts use `ConstArgKind::Path`.

- We explicitly use `ConstArgHasType` for array lengths, rather than
  implicitly relying on anon const type feeding -- this is due to the
  addition of `ConstArgKind::Path`.

- Some tests have their outputs changed, but the changes are for the
  most part minor (including removing duplicate or almost-duplicate
  errors). One test now ICEs, but it is for an incomplete, unstable
  feature and is now tracked at #127009.
2024-07-16 19:27:28 -07:00
Noah Lev 1c49d406b6 Use `ConstArg` for const param defaults
Now everything that actually affects the type system (i.e., excluding
const blocks, enum variant discriminants, etc.) *should* be using
`ConstArg`.
2024-07-16 19:27:28 -07:00
Noah Lev 67fccb7045 Use `ConstArg` for array lengths 2024-07-16 19:27:28 -07:00
Noah Lev 8818708a31 Use `ConstArg` for assoc item constraints 2024-07-16 19:27:28 -07:00
Noah Lev e7c85cb1e0 Setup ty::Const functions for `ConstArg` 2024-07-16 19:27:28 -07:00
Noah Lev 11b144aa98 hir: Create `hir::ConstArgKind` enum
This will allow lowering const params to a dedicated enum variant, rather
than to an `AnonConst` that is later examined during `ty` lowering.
2024-07-16 19:27:28 -07:00
Michael Goulet e86fbcfd70 Move rustc_infer::infer::error_reporting to rustc_infer::error_reporting::infer 2024-07-15 20:16:12 -04:00
Ralf Jung 9d9b55cd2b make invalid_type_param_default lint show up in cargo future-compat reports
and remove the feature gate that silenced the lint
2024-07-15 22:05:45 +02:00
Camille GILLOT b494d98b18 find_field does not need to be a query. 2024-07-14 13:25:25 +00:00
bors 8c39ac9ecc Auto merge of #127575 - chenyukang:yukang-fix-struct-fields-ice, r=compiler-errors
Avoid "no field" error and ICE on recovered ADT variant

Fixes https://github.com/rust-lang/rust/issues/126744
Fixes https://github.com/rust-lang/rust/issues/126344, a more general fix compared with https://github.com/rust-lang/rust/pull/127426

r? `@oli-obk`

From `@compiler-errors` 's comment https://github.com/rust-lang/rust/pull/127502#discussion_r1669538204
Seems most of the ADTs don't have taint, so maybe it's not proper to change `TyCtxt::type_of` query.
2024-07-11 03:12:38 +00:00
yukang 07e6dd95bd report pat no field error no recoverd struct variant 2024-07-11 00:18:47 +08:00
Matthias Krüger a7fe30d82a
Rollup merge of #127094 - Borgerr:E0191-suggestion-correction, r=fmease
E0191 suggestion correction, inserts turbofish

closes #91997
2024-07-10 17:54:26 +02:00
Ashton Hunt 7c88bda1cb E0191 suggestion correction, inserts turbofish without dyn (#91997) 2024-07-09 17:21:31 -06:00
bors 7d640b670e Auto merge of #127358 - oli-obk:taint_itemctxt, r=fmease
Automatically taint when reporting errors from ItemCtxt

This isn't very robust yet, as you need to use `itemctxt.dcx()` instead of `tcx.dcx()` for it to take effect, but it's at least more convenient than sprinkling `set_tainted_by_errors` calls in individual places.

based on https://github.com/rust-lang/rust/pull/127357

r? `@fmease`
2024-07-09 23:03:01 +00:00
bors a2d58197a7 Auto merge of #127493 - compiler-errors:crate-level-import, r=lcnr
Move trait selection error reporting to its own top-level module

This effectively moves `rustc_trait_selection::traits::error_reporting` to `rustc_trait_selection::error_reporting::traits`. There are only a couple of actual changes to the code, like moving the `pretty_impl_header` fn out of the specialization module for privacy reasons.

This is quite pointless on its own, but having `error_reporting` as a top-level module in `rustc_trait_selection` is very important to make sure we have a meaningful file structure for when we move **type** error reporting (and region error reporting, with which it's incredibly entangled currently) into `rustc_trait_selection`. I've opened a tracking issue here: #127492

r? lcnr
2024-07-09 11:23:13 +00:00
Oli Scherer aece06482e Remove HirTyLowerer::set_tainted_by_errors, since it is now redundant 2024-07-09 07:44:17 +00:00
Oli Scherer fd9a92542c Automatically taint when reporting errors from ItemCtxt 2024-07-09 07:44:17 +00:00
bors 5be2ec7245 Auto merge of #127200 - fee1-dead-contrib:trait_def_const_trait, r=compiler-errors
Add `constness` to `TraitDef`

Second attempt at fixing the regression @ https://github.com/rust-lang/rust/pull/120639#issuecomment-2198373716

r? project-const-traits
2024-07-09 06:51:35 +00:00
Michael Goulet fe4c995ccb Move trait selection error reporting to its own top-level module 2024-07-08 16:04:47 -04:00
Oli Scherer af9ab1b026 Remove `structured_errors` module 2024-07-08 19:29:55 +00:00
Oli Scherer 2f0368c902 Remove `StructuredDiag` 2024-07-08 19:29:55 +00:00
Oli Scherer 9e7918f70e Remove another `StructuredDiag` impl 2024-07-08 19:29:55 +00:00
许杰友 Jieyou Xu (Joe) 73593b9aca
Rollup merge of #127452 - fee1-dead-contrib:fx-intrinsic-counting, r=fmease
Fix intrinsic const parameter counting with `effects`

r? project-const-traits
2024-07-08 13:04:34 +08:00
许杰友 Jieyou Xu (Joe) ffb93361b4
Rollup merge of #127439 - compiler-errors:uplift-elaborate, r=lcnr
Uplift elaboration into `rustc_type_ir`

Allows us to deduplicate and consolidate elaboration (including these stupid elaboration duplicate fns i added for pretty printing like 3 years ago) so I'm pretty hyped about this change :3

r? lcnr
2024-07-08 13:04:33 +08:00
许杰友 Jieyou Xu (Joe) 928d71f17b
Rollup merge of #127437 - compiler-errors:uplift-trait-ref-is-knowable, r=lcnr
Uplift trait ref is knowable into `rustc_next_trait_solver`

Self-explanatory. Eliminates one more delegate method.

r? lcnr cc ``@fmease``
2024-07-08 13:04:32 +08:00
bors 89aefb9c53 Auto merge of #127172 - compiler-errors:full-can_eq-everywhere, r=lcnr
Make `can_eq` process obligations (almost) everywhere

Move `can_eq` to an extension trait on `InferCtxt` in `rustc_trait_selection`, and change it so that it processes obligations. This should strengthen it to be more accurate in some cases, but is most important for the new trait solver which delays relating aliases to `AliasRelate` goals. Without this, we always basically just return true when passing aliases to `can_eq`, which can lead to weird errors, for example #127149.

I'm not actually certain if we should *have* `can_eq` be called on the good path. In cases where we need `can_eq`, we probably should just be using a regular probe.

Fixes #127149

r? lcnr
2024-07-07 23:03:48 +00:00
Michael Goulet a982471e07 Uplift trait_ref_is_knowable and friends 2024-07-07 11:10:32 -04:00
Michael Goulet b2e30bdec4 Add fundamental to trait def 2024-07-07 11:10:32 -04:00
Deadbeef 4f54193ccf Fix intrinsic const parameter counting with `effects` 2024-07-07 11:30:03 +00:00
Michael Goulet 58aad3c72c iter_identity is a better name 2024-07-07 00:12:35 -04:00
Michael Goulet cc6c5de39d Import via rustc_type_ir::outlives
We could use rustc_middle::ty::outlives I guess?
2024-07-06 10:47:46 -04:00
Jubilee 853148752f
Rollup merge of #127392 - estebank:arg-type, r=jieyouxu
Use verbose suggestion for changing arg type
2024-07-05 23:23:36 -07:00
Esteban Küber 75692056e1 Use verbose suggestion for changing arg type 2024-07-05 20:58:33 +00:00
Michael Goulet 465e7d546e Rework receiver_is_valid 2024-07-05 11:59:54 -04:00
Michael Goulet fb8d5f1e13 Actually just make can_eq process obligations (almost) everywhere 2024-07-05 11:59:54 -04:00
Michael Goulet fdde66acee Process alias-relate obligations when proving receiver_is_valid 2024-07-05 11:59:52 -04:00
Oli Scherer 7dca61b68b Use `ControlFlow` results for visitors that are only looking for a single value 2024-07-05 15:00:40 +00:00
Matthias Krüger dd42f7a0a6
Rollup merge of #127319 - oli-obk:fail2taint, r=compiler-errors
Remove a use of `StructuredDiag`, which is incompatible with automatic error tainting and error translations

fixes #127219

I want to remove all of `StructuredDiag`, but it's a bit more involved as it is also used from the `ItemCtxt`, which doesn't support tainting yet.
2024-07-04 18:16:26 +02:00
Oli Scherer 0d54fe0d02 Remove a use of `StructuredDiag`, which is incompatible with automatic error tainting and error translations 2024-07-04 12:20:51 +00:00
Esteban Küber f63d2bc657 Better suggestion span for missing type parameter 2024-07-04 02:41:13 +00:00
Deadbeef 46af987072 Add `constness` to `TraitDef` 2024-07-03 15:37:34 +00:00
Boxy 6a00008276 Rewrite dropck 2024-07-02 02:30:38 +01:00
Matthias Krüger b067ee82f8
Rollup merge of #127181 - BoxyUwU:dump_def_parents, r=compiler-errors
Introduce a `rustc_` attribute to dump all the `DefId` parents of a `DefId`

We've run into a bunch of issues with anon consts having the wrong generics and it would have been incredibly helpful to be able to quickly slap a `rustc_` attribute to check what `tcx.parent(` will return on the relevant DefIds.

I wasn't sure of a better way to make this work for anon consts than requiring the attribute to be on the enclosing item and then walking the inside of it to look for any anon consts. This particular method will honestly break at some point when we stop having a `DefId` available for anon consts in hir but that's for another day...

r? ``@compiler-errors``
2024-07-01 08:53:07 +02:00
Boxy 552794410a add `rustc_dump_def_parents` attribute 2024-06-30 19:31:21 +01:00
Deadbeef 34ae56de35 Make `feature(effects)` require `-Znext-solver` 2024-06-30 17:08:10 +00:00
bors 716752ebe6 Auto merge of #127133 - matthiaskrgr:rollup-jxkp3yf, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #123237 (Various rustc_codegen_ssa cleanups)
 - #126960 (Improve error message in tidy)
 - #127002 (Implement `x perf` as a separate tool)
 - #127081 (Add a run-make test that LLD is not being used by default on the x64 beta/stable channel)
 - #127106 (Improve unsafe extern blocks diagnostics)
 - #127110 (Fix a error suggestion for E0121 when using placeholder _ as return types on function signature.)
 - #127114 (fix: prefer `(*p).clone` to `p.clone` if the `p` is a raw pointer)
 - #127118 (Show `used attribute`'s kind for user when find it isn't applied to a `static` variable.)
 - #127122 (Remove uneccessary condition in `div_ceil`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-06-30 02:20:01 +00:00
Matthias Krüger 80cf576f59
Rollup merge of #127110 - surechen:fix_125488_06, r=compiler-errors
Fix a error suggestion for E0121 when using placeholder _ as return types on function signature.

Recommit after refactoring based on comment:
https://github.com/rust-lang/rust/pull/126017#issuecomment-2189149361

But when changing return type's lifetime to `ReError` will affect the subsequent borrow check process and cause test11 in typeck_type_placeholder_item.rs to lost E0515 message.
```rust
fn test11(x: &usize) -> &_ {
//~^ ERROR the placeholder `_` is not allowed within types on item signatures for return types
    &x //~ ERROR cannot return reference to function parameter(this E0515 msg will disappear)
}
```

fixes #125488

r? ``@pnkfelix``
2024-06-29 22:10:58 +02:00
bors ba1d7f4a08 Auto merge of #120639 - fee1-dead-contrib:new-effects-desugaring, r=oli-obk
Implement new effects desugaring

cc `@rust-lang/project-const-traits.` Will write down notes once I have finished.

* [x] See if we want `T: Tr` to desugar into `T: Tr, T::Effects: Compat<true>`
* [x] Fix ICEs on `type Assoc: ~const Tr` and `type Assoc<T: ~const Tr>`
* [ ] add types and traits to minicore test
* [ ] update rustc-dev-guide

Fixes #119717
Fixes #123664
Fixes #124857
Fixes #126148
2024-06-29 20:08:10 +00:00
surechen 50edb32939 Fix a error suggestion for E0121 when using placeholder _ as return types on function signature.
Recommit after refactoring based on comment:
https://github.com/rust-lang/rust/pull/126017#issuecomment-2189149361

But when changing return type's lifetime to `ReError` will affect the subsequent borrow check process and cause test11 in typeck_type_placeholder_item.rs to lost E0515 message.
```rust
fn test11(x: &usize) -> &_ {
//~^ ERROR the placeholder `_` is not allowed within types on item signatures for return types
    &x //~ ERROR cannot return reference to function parameter(this E0515 msg will disappear)
}

```
2024-06-29 14:23:33 +08:00
Deadbeef 65a0bee0b7 address review comments 2024-06-28 15:44:20 +00:00
Deadbeef 0a2330630d general fixups and turn `TODO`s into `FIXME`s 2024-06-28 10:57:35 +00:00
Deadbeef f852a2c173 Implement `Self::Effects: Compat<HOST>` desugaring 2024-06-28 10:57:35 +00:00
Deadbeef b9886c6872 bless tests part 1 2024-06-28 10:57:35 +00:00
Deadbeef 74e7b5bd76 temporarily disable effects on specialization tests 2024-06-28 10:57:35 +00:00
Deadbeef 3637b153f7 move desugaring to item bounds 2024-06-28 10:57:35 +00:00
Deadbeef c7d27a15d0 Implement `Min` trait in new solver 2024-06-28 10:57:35 +00:00
Deadbeef 72e8244e64 implement new effects desugaring 2024-06-28 10:57:35 +00:00
Michael Goulet 81c2c57519 Make queries more explicit 2024-06-27 12:03:57 -04:00
Matthias Krüger 8c6c6a7591
Rollup merge of #126968 - lqd:issue-126670, r=compiler-errors
Don't ICE during RPITIT refinement checking for resolution errors after normalization

#126670 shows a case where resolution errors after normalization can happen during RPITIT refinement checking. Our tests didn't reach this path before, and we explicitly ICEd until we had a test. We can now delay a bug since we're sure it is reachable and have the test from the isue.

The comment I added likely still needs more expert wordsmithing.

r? ``@compiler-errors`` who's making me work during vacation (j/k).
Fixes #126670
2024-06-26 07:50:20 +02:00
Rémy Rakic 6402909f42 delay bug in RPITIT refinement checking with resolution errors 2024-06-25 21:05:54 +00:00
Matthias Krüger 52e6f9ce96
Rollup merge of #126868 - bvanjoi:fix-126764, r=davidtwco
not use offset when there is not ends with brace

Fixes #126764
2024-06-25 18:02:59 +02:00
Michael Goulet f26cc349d9 Split out IntoIterator and non-Iterator constructors for AliasTy/AliasTerm/TraitRef/projection 2024-06-24 11:28:21 -04:00
bohan 594fa01aba not use offset when there is not ends with brace 2024-06-23 23:44:22 +08:00
Matthias Krüger dc9a08f535
Rollup merge of #126552 - fee1-dead-contrib:rmfx, r=compiler-errors
Remove use of const traits (and `feature(effects)`) from stdlib

The current uses are already unsound because they are using non-const impls in const contexts. We can reintroduce them by reverting the commit in this PR, after #120639 lands.

Also, make `effects` an incomplete feature.

cc `@rust-lang/project-const-traits`
r? `@compiler-errors`
2024-06-22 19:33:56 +02:00
Guillaume Gomez 3ed2cd74b5
Rollup merge of #126686 - fmease:dump-preds-n-item-bounds, r=compiler-errors
Add `#[rustc_dump_{predicates,item_bounds}]`

Conflicts with #126668.

As discussed
r? compiler-errors CC ``@fee1-dead``
2024-06-22 12:57:19 +02:00
León Orell Valerian Liehr 38bd7a0fcb
Add `#[rustc_dump_{predicates,item_bounds}]` 2024-06-22 06:34:09 +02:00
Michael Goulet ffd72b1700 Fix remaining cases 2024-06-21 19:00:18 -04:00
Michael Goulet db638ab968 Rename a bunch of things 2024-06-21 12:32:05 -04:00
Deadbeef 02aaea1803 update intrinsic const param counting 2024-06-21 09:23:54 +00:00
León Orell Valerian Liehr bc12972bcd
Slightly refactor the dumping of HIR analysis data 2024-06-20 20:31:32 +02:00
Matthias Krüger ef2e8bfcbf
Rollup merge of #126717 - nnethercote:rustfmt-use-pre-cleanups, r=jieyouxu
Clean up some comments near `use` declarations

#125443 will reformat all `use` declarations in the repository. There are a few edge cases involving comments on `use` declarations that require care. This PR cleans up some clumsy comment cases, taking us a step closer to #125443 being able to merge.

r? ``@lqd``
2024-06-20 14:07:04 +02:00
Matthias Krüger e7be3562b7
Rollup merge of #126620 - oli-obk:taint_errors, r=fee1-dead
Actually taint InferCtxt when a fulfillment error is emitted

And avoid checking the global error counter

fixes #122044
fixes #123255
fixes #123276
fixes #125799
2024-06-20 07:52:43 +02:00
Nicholas Nethercote b104fbec85 Add blank lines after module-level `//` comments.
Similar to the previous commit.
2024-06-20 09:23:20 +10:00
Oli Scherer 393dea8bc3 Allow tracing through item_bounds query invocations on opaques
Previously these caused cycles when printing the result
2024-06-19 08:47:55 +00:00
Oli Scherer 1cb75dc4a9 Remove a hack that isn't needed anymore 2024-06-19 04:41:57 +00:00
许杰友 Jieyou Xu (Joe) 8eb2e5f4c8
Rollup merge of #125293 - dingxiangfei2009:tail-expr-temp-lifetime, r=estebank,davidtwco
Place tail expression behind terminating scope

This PR implements #123739 so that we can do further experiments in nightly.

A little rewrite has been applied to `for await` lowering. It was previously `unsafe { Pin::unchecked_new(into_async_iter(..)) }`. Under the edition 2024 rule, however, `into_async_iter` gets dropped at the end of the `unsafe` block. This presumably the first Edition 2024 migration rule goes by hoisting `into_async_iter(..)` into `match` one level above, so it now looks like the following.
```rust
match into_async_iter($iter_expr) {
  ref mut iter => match unsafe { Pin::unchecked_new(iter) } {
    ...
  }
}
```
2024-06-19 01:51:38 +01: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 c91edc3888 Prefer `dcx` methods over fields or fields' methods 2024-06-18 13:45:08 +00:00
Michael Goulet b1efe1ab5d Rework precise capturing syntax 2024-06-17 22:35:25 -04:00
Ding Xiang Fei 0f8c3f7882
tail expression behind terminating scope 2024-06-18 04:14:43 +08:00
Matthias Krüger 0f2cc21547
Rollup merge of #126417 - beetrees:f16-f128-inline-asm-x86, r=Amanieu
Add `f16` and `f128` inline ASM support for `x86` and `x86-64`

This PR adds `f16` and `f128` input and output support to inline ASM on `x86` and `x86-64`. `f16` vector sizes are taken from [here](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html).

Relevant issue: #125398
Tracking issue: #116909

``@rustbot`` label +F-f16_and_f128
2024-06-15 14:40:48 +02:00
Michael Goulet 93ff86ed7c Use is_lang_item more aggressively 2024-06-14 16:54:29 -04:00
matt rice 1de046fa24 Update for review 2024-06-14 07:53:37 -07:00
Matthias Krüger bfe032334f
Rollup merge of #126054 - veera-sivarajan:bugfix-113073-bound-on-generics-2, r=fee1-dead
`E0229`: Suggest Moving Type Constraints to Type Parameter Declaration

Fixes #113073

This PR suggests  `impl<T: Bound> Trait<T> for Foo` when finding `impl Trait<T: Bound> for Foo`. Tangentially, it also improves a handful of other error messages.

It accomplishes this in two steps:
1. Check if constrained arguments and parameter names appear in the same order and delay emitting "incorrect number of generic arguments" error because it can be confusing for the programmer to see `0 generic arguments provided` when there are `n` constrained generic arguments.

2. Inside `E0229`, suggest declaring the type parameter right after the `impl` keyword by finding the relevant impl block's span for type parameter declaration. This also handles lifetime declarations correctly.

Also, the multi part suggestion doesn't use the fluent error mechanism because translating all the errors to fluent style feels outside the scope of this PR. I will handle it in a separate PR if this gets approved.
2024-06-14 12:23:36 +02:00
beetrees dfc5514527
Add `f16` and `f128` inline ASM support for `x86` and `x86-64` 2024-06-13 16:12:23 +01:00
Veera 5da1b4189e E0229: Suggest Moving Type Constraints to Type Parameter Declaration 2024-06-12 19:32:31 -04:00
Michael Goulet 0d1d6ba58c
Rollup merge of #126340 - fee1-dead-contrib:fix-predicates_of-comments, r=compiler-errors
Fix outdated predacates_of.rs comments

<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.

This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using

    r​? <reviewer name>
-->
2024-06-12 14:26:29 -04:00
Deadbeef 54429cf279 Fix outdated predacates_of.rs comments 2024-06-12 16:19:25 +00:00
Guillaume Gomez c21de3c91e
Rollup merge of #126228 - BoxyUwU:nested_repeat_expr_generics, r=compiler-errors
Provide correct parent for nested anon const

Fixes #126147

99% of this PR is just comments explaining what the issue is.

`tcx.parent(` and `hir().get_parent_item(` give different results as the hir owner for all the hir of anon consts is the enclosing function. I didn't attempt to change that as being a hir owner requires a `DefId` and long term we want to stop creating anon consts' `DefId`s before hir ty lowering.

So i just opted to change `generics_of` to use `tcx.parent` to get the parent for `AnonConst`'s. I'm not entirely sure about this being what we want, it does seem weird that we have two ways of getting the parent of an `AnonConst` and they both give different results.

Alternatively we could just go ahead and make `const_evaluatable_unchecked` a hard error and stop providing generics to repeat exprs. Then this isn't an issue. (The FCW has been around for almost 4 years now)

r? ````@compiler-errors````
2024-06-12 15:44:58 +02:00
bors bbe9a9c20b Auto merge of #126319 - workingjubilee:rollup-lendnud, r=workingjubilee
Rollup of 16 pull requests

Successful merges:

 - #123374 (DOC: Add FFI example for slice::from_raw_parts())
 - #124514 (Recommend to never display zero disambiguators when demangling v0 symbols)
 - #125978 (Cleanup: HIR ty lowering: Consolidate the places that do assoc item probing & access checking)
 - #125980 (Nvptx remove direct passmode)
 - #126187 (For E0277 suggest adding `Result` return type for function when using QuestionMark `?` in the body.)
 - #126210 (docs(core): make more const_ptr doctests assert instead of printing)
 - #126249 (Simplify `[T; N]::try_map` signature)
 - #126256 (Add {{target}} substitution to compiletest)
 - #126263 (Make issue-122805.rs big endian compatible)
 - #126281 (set_env: State the conclusion upfront)
 - #126286 (Make `storage-live.rs` robust against rustc internal changes.)
 - #126287 (Update a cranelift patch file for formatting changes.)
 - #126301 (Use `tidy` to sort crate attributes for all compiler crates.)
 - #126305 (Make PathBuf less Ok with adding UTF-16 then `into_string`)
 - #126310 (Migrate run make prefer rlib)
 - #126314 (fix RELEASES: we do not support upcasting to auto traits)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-06-12 11:10:50 +00: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
Jubilee e7b07ea7a1
Rollup merge of #125978 - fmease:cleanup-hir-ty-lowering-consolidate-assoc-item-access-checking, r=davidtwco
Cleanup: HIR ty lowering: Consolidate the places that do assoc item probing & access checking

Use `probe_assoc_item` (for hygienically probing an assoc item and checking if it's accessible wrt. visibility and stability) for assoc item constraints, too, not just for assoc type paths and make the privacy error translatable.
2024-06-12 03:57:19 -07:00
Oli Scherer 0bc2001879 Require any function with a tait in its signature to actually constrain a hidden type 2024-06-12 08:53:59 +00: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
Boxy bfb7757c3c Correct parent for nested anon consts 2024-06-10 14:32:50 +01:00
bors 1be24d70ce Auto merge of #125918 - oli-obk:const_block_ice, r=compiler-errors
Revert: create const block bodies in typeck via query feeding

as per the discussion in https://github.com/rust-lang/rust/pull/125806#discussion_r1622563948

It was a mistake to try to shoehorn const blocks and some specific anon consts into the same box and feed them during typeck. It turned out not simplifying anything (my hope was that we could feed `type_of` to start avoiding the huge HIR matcher, but that didn't work out), but instead making a few things more fragile.

reverts the const-block-specific parts of https://github.com/rust-lang/rust/pull/124650

`@bors` rollup=never had a small perf impact previously

fixes https://github.com/rust-lang/rust/issues/125846

r? `@compiler-errors`
2024-06-07 09:08:59 +00:00
Oli Scherer cbee17d502 Revert "Create const block DefIds in typeck instead of ast lowering"
This reverts commit ddc5f9b6c1.
2024-06-07 08:33:58 +00:00
Michael Goulet 82ef3ad980 Uplift TypeError 2024-06-06 07:49:47 -04:00
bors 2d28b6384e Auto merge of #124482 - spastorino:unsafe-extern-blocks, r=oli-obk
Unsafe extern blocks

This implements RFC 3484.

Tracking issue #123743 and RFC https://github.com/rust-lang/rfcs/pull/3484

This is better reviewed commit by commit.
2024-06-06 08:14:58 +00:00
Boxy 56092a345b Misc fixes (pattern type lowering, cfi, pretty printing) 2024-06-05 22:25:42 +01:00
Boxy 58feec9b85 Basic removal of `Ty` from places (boring) 2024-06-05 22:25:38 +01:00
Oli Scherer c8a331ac52 Unify optional param info with object lifetime default boolean into an enum that exhaustively supports all call sites 2024-06-05 09:16:55 +00:00
Oli Scherer 78706740d5 Remove `allows_infer` now that every use of it is delegated to `HirTyLowerer` 2024-06-05 09:16:55 +00:00
Oli Scherer 6a2e15a6f0 Only collect infer vars to error about in case infer vars are actually forbidden 2024-06-05 09:16:55 +00:00
Oli Scherer abd308b886 Remove an `Option` and instead eagerly create error lifetimes 2024-06-05 09:16:55 +00:00
Oli Scherer 9d387d14e0 Simplify some code paths and remove an unused field
`ct_infer` and `lower_ty` will correctly result in an error constant or type respectively, as they go through a `HirTyLowerer` method (just like `HirTyLowerer::allow_infer` is a method implemented by both implementors
2024-06-05 08:43:37 +00:00
Oli Scherer dc020ae5d8 Use a `LocalDefId` for `HirTyLowerer::item_def_id`, since we only ever (can) use it for local items 2024-06-05 08:43:37 +00:00
León Orell Valerian Liehr c59a2b2746
Cleanup: HIR ty lowering: Consolidate assoc item access checking 2024-06-04 23:13:16 +02:00
Santiago Pastorino bac72cf7cf
Add safe/unsafe to static inside extern blocks 2024-06-04 14:19:43 -03:00
Santiago Pastorino 2a377122dd
Handle safety keyword for extern block inner items 2024-06-04 14:19:42 -03: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
许杰友 Jieyou Xu (Joe) b477f89041
Rollup merge of #125750 - compiler-errors:expect, r=lcnr
Align `Term` methods with `GenericArg` methods, add `Term::expect_*`

* `Term::ty` -> `Term::as_type`.
* `Term::ct` -> `Term::as_const`.
* Adds `Term::expect_type` and `Term::expect_const`, and uses them in favor of `.ty().unwrap()`, etc.

I could also shorten these to `as_ty` and then do `GenericArg::as_ty` as well, but I do think the `as_` is important to signal that this is a conversion method, and not a getter, like `Const::ty` is.

r? types
2024-06-04 08:25:48 +01:00
许杰友 Jieyou Xu (Joe) 0dc65501cb
Rollup merge of #125608 - oli-obk:subsequent_lifetime_errors, r=BoxyUwU
Avoid follow-up errors if the number of generic parameters already doesn't match

fixes #125604

best reviewed commit-by-commit
2024-06-04 08:25:47 +01:00
bors 90d6255d82 Auto merge of #125380 - compiler-errors:wc-obj-safety, r=oli-obk
Make `WHERE_CLAUSES_OBJECT_SAFETY` a regular object safety violation

#### The issue

In #50781, we have known about unsound `where` clauses in function arguments:

```rust
trait Impossible {}

trait Foo {
    fn impossible(&self)
    where
        Self: Impossible;
}

impl Foo for &() {
    fn impossible(&self)
    where
        Self: Impossible,
    {}
}

// `where` clause satisfied for the object, meaning that the function now *looks* callable.
impl Impossible for dyn Foo {}

fn main() {
    let x: &dyn Foo = &&();
    x.impossible();
}
```

... which currently segfaults at runtime because we try to call a method in the vtable that doesn't exist. :(

#### What did u change

This PR removes the `WHERE_CLAUSES_OBJECT_SAFETY` lint and instead makes it a regular object safety violation. I choose to make this into a hard error immediately rather than a `deny` because of the time that has passed since this lint was authored, and the single (1) regression (see below).

That means that it's OK to mention `where Self: Trait` where clauses in your trait, but making such a trait into a `dyn Trait` object will report an object safety violation just like `where Self: Sized`, etc.

```rust
trait Impossible {}

trait Foo {
    fn impossible(&self)
    where
        Self: Impossible; // <~ This definition is valid, just not object-safe.
}

impl Foo for &() {
    fn impossible(&self)
    where
        Self: Impossible,
    {}
}

fn main() {
    let x: &dyn Foo = &&(); // <~ THIS is where we emit an error.
}
```

#### Regressions

From a recent crater run, there's only one crate that relies on this behavior: https://github.com/rust-lang/rust/pull/124305#issuecomment-2122381740. The crate looks unmaintained and there seems to be no dependents.

#### Further

We may later choose to relax this (e.g. when the where clause is implied by the supertraits of the trait or something), but this is not something I propose to do in this FCP.

For example, given:

```
trait Tr {
  fn f(&self) where Self: Blanket;
}

impl<T: ?Sized> Blanket for T {}
```

Proving that some placeholder `S` implements `S: Blanket` would be sufficient to prove that the same (blanket) impl applies for both `Concerete: Blanket` and `dyn Trait: Blanket`.

Repeating here that I don't think we need to implement this behavior right now.

----

r? lcnr
2024-06-04 02:34:20 +00:00
Michael Goulet 273b990554 Align Term methods with GenericArg methods 2024-06-03 20:36:27 -04:00
Michael Goulet a41c44f21c Nits and formatting 2024-06-03 10:02:08 -04:00
Michael Goulet 511f1cf7c8 check_is_object_safe -> is_object_safe 2024-06-03 09:49:30 -04:00
Oli Scherer d498eb5937 Provide previous generic arguments to `provided_kind` 2024-06-03 13:48:54 +00:00
Oli Scherer 108a1e5f4b Always provide previous generic arguments 2024-06-03 13:45:36 +00:00
Oli Scherer 063b26af6b Explain some code duplication 2024-06-03 13:28:49 +00: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 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
Oli Scherer adb2ac0165 Mark all extraneous generic args as errors 2024-06-03 13:21:17 +00:00
Oli Scherer 2e3842b6d0 Mark all missing generic args as errors 2024-06-03 13:16:56 +00:00
Oli Scherer 24af952ef7 Store indices of generic args instead of spans, as the actual entries are unused, just the number of entries is checked.
The indices will be used in a follow-up commit
2024-06-03 13:06:59 +00:00
Oli Scherer 4dec6bbcb3 Avoid an `Option` that is always `Some` 2024-06-03 13:05:52 +00:00
Oli Scherer 61c4b7f1a7 Hide some follow-up errors 2024-06-03 13:03:53 +00: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
Mark Rousskov 95e073234f Deduplicate supertrait_def_ids code 2024-06-01 07:50:32 -04:00
bors 99cb42c296 Auto merge of #124662 - zetanumbers:needs_async_drop, r=oli-obk
Implement `needs_async_drop` in rustc and optimize async drop glue

This PR expands on #121801 and implements `Ty::needs_async_drop` which works almost exactly the same as `Ty::needs_drop`, which is needed for #123948.

Also made compiler's async drop code to look more like compiler's regular drop code, which enabled me to write an optimization where types which do not use `AsyncDrop` can simply forward async drop glue to `drop_in_place`. This made size of the async block from the [async_drop test](67980dd6fb/tests/ui/async-await/async-drop.rs) to decrease by 12%.
2024-05-31 10:12:24 +00:00
Matthias Krüger ab55d42b74
Rollup merge of #125786 - compiler-errors:fold-item-bounds, r=lcnr
Fold item bounds before proving them in `check_type_bounds` in new solver

Vaguely confident that this is sufficient to prevent rust-lang/trait-system-refactor-initiative#46 and rust-lang/trait-system-refactor-initiative#62.

This is not the "correct" solution, but will probably suffice until coinduction, at which point we implement the right solution (`check_type_bounds` must prove `Assoc<...> alias-eq ConcreteType`, normalizing requires proving item bounds).

r? lcnr
2024-05-31 08:50: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
Michael Goulet 2f4b7dc047 Fold item bound before checking that they hold 2024-05-30 15:52:29 -04:00
bors d43930dab3 Auto merge of #125711 - oli-obk:const_block_ice2, r=Nadrieril
Make `body_owned_by` return the `Body` instead of just the `BodyId`

fixes #125677

Almost all `body_owned_by` callers immediately called `body`, too, so just return `Body` directly.

This makes the inline-const query feeding more robust, as all calls to `body_owned_by` will now yield a body for inline consts, too.

I have not yet figured out a good way to make `tcx.hir().body()` return an inline-const body, but that can be done as a follow-up
2024-05-30 08:00:11 +00: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
Michael Goulet a9c7e024c0 Add lang item for Future::Output 2024-05-29 14:22:56 -04: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 ceb45d5519 Don't require `visit_body` to take a lifetime that must outlive the function call 2024-05-29 10:04:08 +00:00
Daria Sukhonina a47173c4f7 Start implementing needs_async_drop and related 2024-05-29 12:50:44 +03:00
Scott McMurray 459ce3f6bb Add an intrinsic for `ptr::metadata` 2024-05-28 09:28:51 -07:00
Oli Scherer ddc5f9b6c1 Create const block DefIds in typeck instead of ast lowering 2024-05-28 13:38:43 +00:00
Oli Scherer a04ac26a9d Allow type_of to return partially non-error types if the type was already tainted 2024-05-28 11:55:20 +00:00
Oli Scherer 53e3c3271f Make body-visiting logic reusable 2024-05-28 11:36:30 +00:00
Guillaume Gomez a9c125f864
Rollup merge of #125597 - compiler-errors:early-binder, r=jackh726
Uplift `EarlyBinder` into `rustc_type_ir`

We also need to give `EarlyBinder` a `'tcx` param, so that we can carry the `Interner` in the `EarlyBinder` too. This is necessary because otherwise we have an unconstrained `I: Interner` parameter in many of the `EarlyBinder`'s inherent impls.

I also generally think that this is desirable to have, in case we later want to track some state in the `EarlyBinder`.

r? lcnr
2024-05-27 13:10:36 +02:00
bors b582f807fa Auto merge of #125410 - fmease:adj-lint-diag-api, r=nnethercote
[perf] Delay the construction of early lint diag structs

Attacks some of the perf regressions from https://github.com/rust-lang/rust/pull/124417#issuecomment-2123700666.

See individual commits for details. The first three commits are not strictly necessary.
However, the 2nd one (06bc4fc671, *Remove `LintDiagnostic::msg`*) makes the main change way nicer to implement.
It's also pretty sweet on its own if I may say so myself.
2024-05-27 08:44:12 +00:00
bors fec98b3bbc Auto merge of #125468 - BoxyUwU:remove_defid_from_regionparam, r=compiler-errors
Remove `DefId` from `EarlyParamRegion`

Currently we represent usages of `Region` parameters via the `ReEarlyParam` or `ReLateParam` variants. The `ReEarlyParam` is effectively equivalent to `TyKind::Param` and `ConstKind::Param` (i.e. it stores a `Symbol` and a `u32` index) however it also stores a `DefId` for the definition of the lifetime parameter.

This was used in roughly two places:
- Borrowck diagnostics instead of threading the appropriate `body_id` down to relevant locations. Interestingly there were already some places that had to pass down a `DefId` manually.
- Some opaque type checking logic was using the `DefId` field to track captured lifetimes

I've split this PR up into a commit for generate rote changes to diagnostics code to pass around a `DefId` manually everywhere, and another commit for the opaque type related changes which likely require more careful review as they might change the semantics of lints/errors.

Instead of manually passing the `DefId` around everywhere I previously tried to bundle it in with `TypeErrCtxt` but ran into issues with some call sites of `infcx.err_ctxt` being unable to provide a `DefId`, particularly places involved with trait solving and normalization. It might be worth investigating adding some new wrapper type to pass this around everywhere but I think this might be acceptable for now.

This pr also has the effect of reducing the size of `EarlyParamRegion` from 16 bytes -> 8 bytes. I wouldn't expect this to have any direct performance improvement however, other variants of `RegionKind` over `8` bytes are all because they contain a `BoundRegionKind` which is, as far as I know, mostly there for diagnostics. If we're ever able to remove this it would shrink the `RegionKind` type from `24` bytes to `12` (and with clever bit packing we might be able to get it to `8` bytes). I am curious what the performance impact would be of removing interning of `Region`'s if we ever manage to shrink `RegionKind` that much.

Sidenote: by removing the `DefId` the `Debug` output for `Region` has gotten significantly nicer. As an example see this opaque type debug print before vs after this PR:
`Opaque(DefId(0:13 ~ impl_trait_captures[aeb9]::foo::{opaque#0}), [DefId(0:9 ~ impl_trait_captures[aeb9]::foo::'a)_'a/#0, T, DefId(0:9 ~ impl_trait_captures[aeb9]::foo::'a)_'a/#0])`
`Opaque(DefId(0:13 ~ impl_trait_captures[aeb9]::foo::{opaque#0}), ['a/#0, T, 'a/#0])`

r? `@compiler-errors` (I would like someone who understands the opaque type setup to atleast review the type system commit, but the rest is likely reviewable by anyone)
2024-05-27 06:36:57 +00:00
Michael Goulet bbcdb4fd3e Give EarlyBinder a tcx parameter
We are gonna need it to uplift EarlyBinder
2024-05-26 20:04:05 -04:00
Boxy fe2d7794ca Remove `DefId` from `EarlyParamRegion` (tedium/diagnostics) 2024-05-24 18:06:53 +01:00
Boxy bd6344d829 Remove `DefId` from `EarlyParamRegion` (type system) 2024-05-24 17:33:48 +01:00
Matthias Krüger 4af1c31fcf
Rollup merge of #125156 - zachs18:for_loops_over_fallibles_behind_refs, r=Nilstrieb
Expand `for_loops_over_fallibles` lint to lint on fallibles behind references.

Extends the scope of the (warn-by-default) lint `for_loops_over_fallibles` from just `for _ in x` where `x: Option<_>/Result<_, _>` to also cover `x: &(mut) Option<_>/Result<_>`

```rs
fn main() {
    // Current lints
    for _ in Some(42) {}
    for _ in Ok::<_, i32>(42) {}

    // New lints
    for _ in &Some(42) {}
    for _ in &mut Some(42) {}
    for _ in &Ok::<_, i32>(42) {}
    for _ in &mut Ok::<_, i32>(42) {}

    // Should not lint
    for _ in Some(42).into_iter() {}
    for _ in Some(42).iter() {}
    for _ in Some(42).iter_mut() {}
    for _ in Ok::<_, i32>(42).into_iter() {}
    for _ in Ok::<_, i32>(42).iter() {}
    for _ in Ok::<_, i32>(42).iter_mut() {}
}
```

<details><summary><code>cargo build</code> diff</summary>

```diff
diff --git a/old.out b/new.out
index 84215aa..ca195a7 100644
--- a/old.out
+++ b/new.out
`@@` -1,33 +1,93 `@@`
 warning: for loop over an `Option`. This is more readably written as an `if let` statement
  --> src/main.rs:3:14
   |
 3 |     for _ in Some(42) {}
   |              ^^^^^^^^
   |
   = note: `#[warn(for_loops_over_fallibles)]` on by default
 help: to check pattern in a loop use `while let`
   |
 3 |     while let Some(_) = Some(42) {}
   |     ~~~~~~~~~~~~~~~ ~~~
 help: consider using `if let` to clear intent
   |
 3 |     if let Some(_) = Some(42) {}
   |     ~~~~~~~~~~~~ ~~~

 warning: for loop over a `Result`. This is more readably written as an `if let` statement
  --> src/main.rs:4:14
   |
 4 |     for _ in Ok::<_, i32>(42) {}
   |              ^^^^^^^^^^^^^^^^
   |
 help: to check pattern in a loop use `while let`
   |
 4 |     while let Ok(_) = Ok::<_, i32>(42) {}
   |     ~~~~~~~~~~~~~ ~~~
 help: consider using `if let` to clear intent
   |
 4 |     if let Ok(_) = Ok::<_, i32>(42) {}
   |     ~~~~~~~~~~ ~~~

-warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 2 warnings
-    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.04s
+warning: for loop over a `&Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:7:14
+  |
+7 |     for _ in &Some(42) {}
+  |              ^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+7 |     while let Some(_) = &Some(42) {}
+  |     ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+7 |     if let Some(_) = &Some(42) {}
+  |     ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:8:14
+  |
+8 |     for _ in &mut Some(42) {}
+  |              ^^^^^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+8 |     while let Some(_) = &mut Some(42) {}
+  |     ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+8 |     if let Some(_) = &mut Some(42) {}
+  |     ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&Result`. This is more readably written as an `if let` statement
+ --> src/main.rs:9:14
+  |
+9 |     for _ in &Ok::<_, i32>(42) {}
+  |              ^^^^^^^^^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+9 |     while let Ok(_) = &Ok::<_, i32>(42) {}
+  |     ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+9 |     if let Ok(_) = &Ok::<_, i32>(42) {}
+  |     ~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Result`. This is more readably written as an `if let` statement
+  --> src/main.rs:10:14
+   |
+10 |     for _ in &mut Ok::<_, i32>(42) {}
+   |              ^^^^^^^^^^^^^^^^^^^^^
+   |
+help: to check pattern in a loop use `while let`
+   |
+10 |     while let Ok(_) = &mut Ok::<_, i32>(42) {}
+   |     ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+   |
+10 |     if let Ok(_) = &mut Ok::<_, i32>(42) {}
+   |     ~~~~~~~~~~ ~~~
+
+warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 6 warnings
+    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s

```

</details>

-----

Question:

* ~~Currently, the article `an` is used for `&Option`, and `&mut Option` in the lint diagnostic, since that's what `Option` uses. Is this okay or should it be changed? (likewise, `a` is used for `&Result` and `&mut Result`)~~ The article `a` is used for `&Option`, `&mut Option`, `&Result`, `&mut Result` and (as before) `Result`. Only `Option` uses `an` (as before).

`@rustbot` label +A-lint
2024-05-23 07:41:17 +02:00
León Orell Valerian Liehr 06bc4fc671
Remove `LintDiagnostic::msg`
* instead simply set the primary message inside the lint decorator functions
* it used to be this way before [#]101986 which introduced `msg` to prevent
  good path delayed bugs (which no longer exist) from firing under certain
  circumstances when lints were suppressed / silenced
* this is no longer necessary for various reasons I presume
* it shaves off complexity and makes further changes easier to implement
2024-05-23 04:08:35 +02:00
León Orell Valerian Liehr b3604de1df
Rollup merge of #125015 - fmease:pat-tys-proh-gen-args-on-ct-params, r=spastorino
Pattern types: Prohibit generic args on const params

Addresses https://github.com/rust-lang/rust/pull/123689/files#r1562676629.

NB: Technically speaking, *not* prohibiting generics args on const params is not a bug as `pattern_types` is an *internal* feature and as such any uncaught misuses of it are considered to be the fault of the user. However, permitting this makes me slightly uncomfortable esp. since we might want to make pattern types available to the public at some point and I don't want this oversight to be able to slip into the language (for comparison, ICEs triggered by the use of internal features are like super fine).

Furthermore, this is an ad hoc fix. A more general fix would be changing the representation of the pattern part of pattern types in such a way that it can reuse preexisting lowering routines for exprs / anon consts. See also this [Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/pattern.20type.20HIR.20nodes/near/432410768) and #124650.

Also note that we currently don't properly typeck the pattern of pat tys. This however is out of scope for this PR.

cc ``@oli-obk``
r? ``@spastorino`` as discussed
2024-05-22 19:04:44 +02:00
bors bec10295d4 Auto merge of #125335 - compiler-errors:binder, r=lcnr
Uplift `Binder`, `OutlivesPredicate` into `rustc_type_ir`

Almost done with all the types 🙏

r? lcnr
2024-05-22 08:33:34 +00:00
Michael Goulet 1c8230ea3c Uplift OutlivesPredicate, remove a bunch of unnecessary associated types from Interner 2024-05-21 17:00:45 -04:00
Michael Goulet 28ce588321 Uplift binder 2024-05-21 17:00:45 -04:00
bors 6715446db6 Auto merge of #125358 - matthiaskrgr:rollup-mx841tg, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #124570 (Miscellaneous cleanups)
 - #124772 (Refactor documentation for Apple targets)
 - #125011 (Add opt-for-size core lib feature flag)
 - #125218 (Migrate `run-make/no-intermediate-extras` to new `rmake.rs`)
 - #125225 (Use functions from `crt_externs.h` on iOS/tvOS/watchOS/visionOS)
 - #125266 (compiler: add simd_ctpop intrinsic)
 - #125348 (Small fixes to `std::path::absolute` docs)

Failed merges:

 - #125296 (Fix `unexpected_cfgs` lint on std)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-21 12:50:09 +00:00
Matthias Krüger fd975f75fa
Rollup merge of #125266 - workingjubilee:stream-plastic-love, r=RalfJung,nikic
compiler: add simd_ctpop intrinsic

Fairly straightforward addition.

cc `@rust-lang/opsem` new (extremely boring) intrinsic
2024-05-21 12:47:06 +02:00
Michael Goulet a502e7ac1d Implement BOXED_SLICE_INTO_ITER 2024-05-20 19:21:30 -04:00
Santiago Pastorino 4501ae89f1
Add and use generics.is_empty() and generics.is_own_empty, rather than using generics' attributes 2024-05-19 11:10:56 -03:00
Jubilee Young 1914c722b5 compiler: add simd_ctpop intrinsic 2024-05-18 18:11:20 -07: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
Santiago Pastorino 6b46a919e1
Rename Unsafe to Safety 2024-05-17 18:33:37 -03:00
Michael Goulet 2025e44ef8 to_opt_poly_X_pred -> as_X_clause 2024-05-17 12:58:33 -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
Zachary S 0e467596ff Fix more new for_loops_over_fallibles hits in compiler. 2024-05-15 12:30:30 -05:00
Michael Goulet 1529c661e4 Warn against redundant use<...> 2024-05-13 23:57:56 -04:00
bors 34582118af Auto merge of #125076 - compiler-errors:alias-term, r=lcnr
Split out `ty::AliasTerm` from `ty::AliasTy`

Splitting out `AliasTerm` (for use in project and normalizes goals) and `AliasTy` (for use in `ty::Alias`)

r? lcnr
2024-05-13 22:20:43 +00:00
Michael Goulet fa84018c2e Apply nits 2024-05-13 16:55:58 -04:00
Michael Goulet 3bcdf3058e split out AliasTy -> AliasTerm 2024-05-13 11:59:42 -04:00
Nicholas Nethercote f59348ff09 Remove `extern crate rustc_middle` from `rustc_hir_analysis`. 2024-05-13 08:04:47 +10:00
Michael Goulet 905f565824 Apply nits, uplift ExistentialPredicate too 2024-05-11 18:20:00 -04:00
León Orell Valerian Liehr 7faa879486
Pattern types: Prohibit generic args on const params 2024-05-11 16:12:43 +02: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 4bde8a8f4b Remove glob imports for ObligationCauseCode 2024-05-10 10:42:56 -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
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
Nicholas Nethercote fd91925bce Add `ErrorGuaranteed` to `Recovered::Yes` and use it more.
The starting point for this was identical comments on two different
fields, in `ast::VariantData::Struct` and `hir::VariantData::Struct`:
```
    // FIXME: investigate making this a `Option<ErrorGuaranteed>`
    recovered: bool
```
I tried that, and then found that I needed to add an `ErrorGuaranteed`
to `Recovered::Yes`. Then I ended up using `Recovered` instead of
`Option<ErrorGuaranteed>` for these two places and elsewhere, which
required moving `ErrorGuaranteed` from `rustc_parse` to `rustc_ast`.

This makes things more consistent, because `Recovered` is used in more
places, and there are fewer uses of `bool` and
`Option<ErrorGuaranteed>`. And safer, because it's difficult/impossible
to set `recovered` to `Recovered::Yes` without having emitted an error.
2024-05-09 20:12:07 +10:00
bors faefc618cf Auto merge of #124219 - gurry:122989-ice-unexpected-anon-const, r=compiler-errors
Do not ICE on `AnonConst`s in `diagnostic_hir_wf_check`

Fixes #122989

Below is the snippet from #122989 that ICEs:
```rust
trait Traitor<const N: N<2> = 1, const N: N<2> = N> {
    fn N(&N) -> N<2> {
        M
    }
}

trait N<const N: Traitor<2> = 12> {}
```

The `AnonConst` that triggers the ICE is the `2` in the param `const N: N<2> = 1`. The currently existing code in `diagnostic_hir_wf_check` deals only with `AnonConst`s that are default values of some param, but  the `2` is not a default value. It is just an `AnonConst` HIR node inside a `TraitRef` HIR node corresponding to `N<2>`. Therefore the existing code cannot handle it and this PR ensures that it does.
2024-05-07 20:01:18 +00:00
Michael Goulet a55d30f53c
Rollup merge of #124687 - fee1-dead-contrib:private-clauses, r=compiler-errors
Make `Bounds.clauses` private

Construct it through `Bounds::default()`, then consume the clauses via the method `Bounds::clauses()`.

This helps with effects desugaring where `clauses()` is not only the clauses within the `clauses` field.
2024-05-03 23:34:25 -04:00
Deadbeef 921e74fa57 Make `Bounds.clauses` private 2024-05-04 10:20:39 +08:00
bors 09cd00fea4 Auto merge of #124401 - oli-obk:some_hir_cleanups, r=cjgillot
Some hir cleanups

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

r? compiler
2024-05-04 00:32:27 +00:00
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
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 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 2a1d748254
Replace item names containing an error code with something more meaningful
or inline such functions if useless.
2024-04-30 22:27:19 +02:00
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
Oli Scherer fea1fe7f01 Avoid some `def_span` query calls 2024-04-29 09:48:19 +00:00
Gurinder Singh c62bc31b16 Fix ICE on invalid const param types 2024-04-27 09:36:38 +05:30
Oli Scherer 4dc46f7f17 put `hir::AnonConst` on the hir arena 2024-04-26 12:57:02 +00:00
bors 6a9758d4f3 Auto merge of #124058 - TechVest:master, r=fmease
Fix some typos in comments
2024-04-25 13:02:08 +00:00
TechVest 45df09b7de Fix some typos in comments
Signed-off-by: TechVest <techdashen@qq.com>
2024-04-25 10:47:24 +08:00
bors 5557f8c9d0 Auto merge of #122500 - petrochenkov:deleg, r=fmease
delegation: Support renaming, and async, const, extern "ABI" and C-variadic functions

Also allow delegating to functions with opaque types (`impl Trait`).
The delegation item will refer to the original opaque type from the callee, fresh opaque type won't be created, which seems like a reasonable behavior.
(Such delegation items will cause query cycles when used in trait impls, but it can be fixed later.)

Part of https://github.com/rust-lang/rust/issues/118212.
2024-04-24 11:57:35 +00:00
Vadim Petrochenkov 7b7c26f09b delegation: Support async, const, extern "ABI" and C-variadic functions
Also allow `impl Trait` in delegated functions.
The delegation item will refer to the original opaque type from the callee, fresh opaque type won't be created.
2024-04-23 23:05:39 +03:00
bors 40dcd796d0 Auto merge of #124302 - matthiaskrgr:rollup-2aya8n8, r=matthiaskrgr
Rollup of 3 pull requests

Successful merges:

 - #124003 (Dellvmize some intrinsics (use `u32` instead of `Self` in some integer intrinsics))
 - #124169 (Don't fatal when calling `expect_one_of` when recovering arg in `parse_seq`)
 - #124286 (Subtree sync for rustc_codegen_cranelift)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-23 18:23:46 +00:00
Matthias Krüger 918304b190
Rollup merge of #124003 - WaffleLapkin:dellvmization, r=scottmcm,RalfJung,antoyo
Dellvmize some intrinsics (use `u32` instead of `Self` in some integer intrinsics)

This implements https://github.com/rust-lang/compiler-team/issues/693 minus what was implemented in #123226.

Note: I decided to _not_ change `shl`/... builder methods, as it just doesn't seem worth it.

r? ``@scottmcm``
2024-04-23 20:17:51 +02:00
León Orell Valerian Liehr e15d6f9d85
Rollup merge of #123993 - compiler-errors:coroutine-obl, r=lcnr
Do `check_coroutine_obligations` once per typeck root

We only need to do `check_coroutine_obligations` once per typeck root, especially since the new solver can't really (easily) associate which obligations correspond to which coroutines.

This requires us to move the checks for sized coroutine fields into `mir_coroutine_witnesses`, but that's fine imo.

r? lcnr
2024-04-23 17:25:16 +02:00
León Orell Valerian Liehr 68939f7826
Rollup merge of #122591 - gurry:122162-impl-type-binding-suggestion, r=fmease
Suggest using type args directly instead of equality constraint

When type arguments are written erroneously using an equality constraint we suggest specifying them directly without the equality constraint.

Fixes #122162

Changes the diagnostic in the issue from:
```rust
error[E0229]: associated type bindings are not allowed here
9 | impl std::cmp::PartialEq<Rhs = T> for S {
  |                          ^^^^^^^ associated type not allowed here
  |
```
to
```rust
error[E0229]: associated type bindings are not allowed here
9 | impl std::cmp::PartialEq<Rhs = T> for S {
  |                          ^^^^^^^ associated type not allowed here
  |
help: to use `T` as a generic argument specify it directly
  |
  |      impl std::cmp::PartialEq<T> for S {
  |                               ~
```
2024-04-23 17:25:14 +02:00
Matthias Krüger 802f629cfe
Rollup merge of #124288 - fee1-dead-contrib:rm_inner, r=fmease
remove `push_trait_bound_inner`

Don't see a use for it.
2024-04-23 12:10:27 +02:00
Matthias Krüger 36316df9fe
Rollup merge of #124067 - RalfJung:weak-lang-items, r=davidtwco
weak lang items are not allowed to be #[track_caller]

For instance the panic handler will be called via this import
```rust
        extern "Rust" {
            #[lang = "panic_impl"]
            fn panic_impl(pi: &PanicInfo<'_>) -> !;
        }
```
A `#[track_caller]` would add an extra argument and thus make this the wrong signature.

The 2nd commit is a consistency rename; based on the docs [here](https://doc.rust-lang.org/unstable-book/language-features/lang-items.html) and [here](https://rustc-dev-guide.rust-lang.org/lang-items.html) I figured "lang item" is more widely used. (In the compiler output, "lang item" and "language item" seem to be pretty even.)
2024-04-23 12:10:25 +02:00
Deadbeef 7f3c83126a remove `push_trait_bound_inner` 2024-04-23 17:54:58 +08:00
Guillaume Gomez 6a326d889a
Rollup merge of #124230 - reitermarkus:generic-nonzero-stable, r=dtolnay
Stabilize generic `NonZero`.

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

r? `@dtolnay`
2024-04-22 20:26:00 +02:00
Markus Reiter 33e68aadc9
Stabilize generic `NonZero`. 2024-04-22 18:48:47 +02:00
Gurinder Singh 446f78d051 Do not ICE on `AnonConst`s in `diagnostic_hir_wf_check` 2024-04-22 10:31:32 +05:30
bors fb898629a2 Auto merge of #124241 - matthiaskrgr:rollup-xhu90xr, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #123840 (Add an intrinsic for `ptr::from_raw_parts(_mut)`)
 - #124224 (cleanup: unnecessary clone during lower generics args)
 - #124229 (Add gnullvm targets to manifest)
 - #124231 (remove from reviewers)
 - #124235 (Move some tests)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-21 21:08:03 +00:00
Matthias Krüger cd92422180
Rollup merge of #124224 - bvanjoi:cleanup, r=fmease
cleanup: unnecessary clone during lower generics args
2024-04-21 21:56:32 +02:00
bors 1b3fba066c Auto merge of #124203 - lukas-code:delete-deleting-caches, r=compiler-errors
fix normalizing in different `ParamEnv`s with the same `InferCtxt`

This PR changes the key of the projection cache from just `AliasTy` to `(AliasTy, ParamEnv)` to allow normalizing in different `ParamEnv`s without resetting caches. Previously, normalizing the same alias in different param envs would always reuse the cached result from the first normalization, which is incorrect if the projection clauses in the param env have changed.

Fixing this bug allows us to get rid of `InferCtxt::clear_caches`, which was only used by the `AutoTraitFinder`, because it requires normalizing in different param envs.

r? `@fmease`
2024-04-21 19:05:08 +00:00
Scott McMurray 4f4442655e Add an intrinsic that lowers to AggregateKind::RawPtr 2024-04-21 11:08:37 -07:00
Lukas Markeffsky 5a2b335e49 also remap RPITITs nested in other types back to their opaques 2024-04-21 18:04:50 +02:00
bohan 2d5a226f8f cleanup: unnecessary clone during lower generics args 2024-04-21 20:40:44 +08:00
Michael Goulet 57085a06d9 Explicitly mention `Self` 2024-04-20 11:39:43 -04:00
Michael Goulet fa0428c9d0 Flip spans for precise capturing syntax not capturing a ty/ct param 2024-04-20 10:35:04 -04:00
Matthias Krüger ff9a0b19ff
Rollup merge of #124104 - compiler-errors:parent-generic-use, r=oli-obk
Fix capturing duplicated lifetimes via parent in `precise_captures` (`impl use<'...>`)

For technical reasons related to the way that `Self` and `T::Assoc` are lowered from HIR -> `rustc_middle::ty`, an opaque may mention in its bounds both the original early-bound lifetime from the parent `impl`/`fn`, *and* the *duplicated* early-bound lifetime on the opaque.

This is fine -- and has been fine since `@cjgillot` rewrote the way we handled opaque lifetime captures, and we went further to allow this behavior explicitly in https://github.com/rust-lang/rust/pull/115659. It's worthwhile to read this PR's technical section to recall how this duplication works and when it acts surprisingly.

The problem here is that the check that make sure that `impl use<'a, 'b>` lists all of the opaque's captured lifetimes wasn't smart enough to consider both these captured lifetimes and the original lifetimes they're duplicated from to be equal. This PR fixes that.

r? oli-obk
2024-04-20 11:10:31 +02:00
Michael Goulet 5daf58ffc1 Fix capturing duplicated lifetimes via parent 2024-04-19 14:12:21 -04:00
Matthias Krüger 26d4b1bfba
Rollup merge of #124106 - compiler-errors:tait-lifetime-dedup, r=oli-obk
Don't repeatedly duplicate TAIT lifetimes for each subsequently nested TAIT

Make it so that nested TAITs inherit the lifetimes from their parent item, not their parent TAIT. This is because we don't need to re-duplicate lifetimes for nested TAITs over and over, since the only lifetimes they can capture are from the parent item anyways.

This mirrors how RPITs work. This is **not** a functional change that should be observable, since the whole point of duplicating lifetimes and marking the shadowed ones (and uncaptured ones) as bivariant is designed to *not* be observable.

r? oli-obk
2024-04-19 19:30:49 +02:00
Matthias Krüger 7add0bdf7e
Rollup merge of #124047 - Jules-Bertholet:match-ergonomics-cleanups, r=Nadrieril
Match ergonomics 2024: miscellaneous code cleanups

- Store `ByRef` instead of `BindingAnnotation` in `PatInfo`
- Rename `BindingAnnotation` to `BindingMode`

r? ``@Nadrieril``

cc #123076

``@rustbot`` label A-patterns
2024-04-18 08:37:48 +02:00
Michael Goulet ffb4206577 Don't repeatedly duplicate TAIT lifetimes for each subsequently nested TAIT 2024-04-17 22:29:59 -04:00
bors 00ed4edb44 Auto merge of #123674 - oli-obk:bogus_note, r=estebank
Silence some follow-up errors on trait impls in case the trait has conflicting or otherwise incoherent impls

fixes #123292

Also removes a bunch of extra diagnostics that were introduced in https://github.com/rust-lang/rust/pull/121154 and https://github.com/rust-lang/rust/pull/120558
2024-04-17 14:25:10 +00:00
Jules Bertholet 2a4624ddd1
Rename `BindingAnnotation` to `BindingMode` 2024-04-17 09:34:39 -04:00