Commit Graph

2192 Commits

Author SHA1 Message Date
Nicholas Nethercote
c4717cc9d1 Shrink TyKind::FnPtr.
By splitting the `FnSig` within `TyKind::FnPtr` into `FnSigTys` and
`FnHeader`, which can be packed more efficiently. This reduces the size
of the hot `TyKind` type from 32 bytes to 24 bytes on 64-bit platforms.
This reduces peak memory usage by a few percent on some benchmarks. It
also reduces cache misses and page faults similarly, though this doesn't
translate to clear cycles or wall-time improvements on CI.
2024-08-09 14:33:25 +10:00
Guillaume Gomez
a6caceee4d
Rollup merge of #128424 - fee1-dead-contrib:fx-clean, r=oli-obk
minor `effects` cleanups

* remove the fixme comment about not needing defaults because it turns out we do need defaults (if I made it None instead it would ice a bunch of tests)
* remove the part that special cased trait args when lowering them. This is now historical because effects doesn't add host args to traits anymore (we use associated types now)
2024-08-07 15:59:35 +02:00
Matthias Krüger
333c63b9fc
Rollup merge of #128377 - veera-sivarajan:fix-128249, r=davidtwco
Fix ICE Caused by Incorrectly Delaying E0107

Fixes  #128249

For the following code:
```rust
trait Foo<T> {}
impl Foo<T: Default> for u8 {}
```
#126054 added some logic to delay emitting E0107 as the names of associated type `T` in the impl header and generic parameter `T` in `trait Foo` match.

But it failed to ensure whether such unexpected associated type bounds are coming from a impl block header. This caused an ICE as the compiler was delaying E0107 for code like:
```rust
trait Trait<Type> {
    type Type;

    fn method(&self) -> impl Trait<Type: '_>;
}
```
because it assumed the associated type bound `Type: '_` is for the generic parameter `Type` in `trait Trait` since the names are same.

This PR adds a check to ensure that E0107 is delayed only in the context of impl block header.
2024-08-06 20:23:39 +02:00
bors
c9687a95a6 Auto merge of #125558 - Amanieu:const-asm-type, r=lcnr
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.

<!--
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-08-06 01:20:43 +00:00
Matthias Krüger
cc61dc8b2d
Rollup merge of #127655 - RalfJung:invalid_type_param_default, r=compiler-errors
turn `invalid_type_param_default` into a `FutureReleaseErrorReportInDeps`

`````@rust-lang/types````` I assume the plan is still to disallow this? It has been a future-compat lint for a long time, seems ripe to go for hard error.

However, turns out that outright removing it right now would lead to [tons of crater regressions](https://github.com/rust-lang/rust/pull/127655#issuecomment-2228285460), so for now this PR just makes this future-compat lint show up in cargo's reports, so people are warned when they use a dependency that is affected by this.

Fixes https://github.com/rust-lang/rust/issues/27336 by removing the feature gate (so there's no way to silence the lint even on nightly)
CC https://github.com/rust-lang/rust/issues/36887
2024-08-05 05:40:19 +02:00
Bryanskiy
9b097b2d44 Delegation: second attempt to improve perf 2024-07-31 18:58:04 +03:00
Deadbeef
ec77db83b2 minor effects cleanups 2024-07-31 03:29:10 +00:00
bors
1ddedbaa59 Auto merge of #125929 - Bryanskiy:delegation-generics-3, r=petrochenkov
Delegation: support generics for delegation from free functions

(The PR was split from https://github.com/rust-lang/rust/pull/123958, explainer - https://github.com/Bryanskiy/posts/blob/master/delegation%20in%20generic%20contexts.md)

This PR implements generics inheritance from free functions to free functions and trait methods.

#### free functions to free functions:

```rust
fn to_reuse<T: Clone>(_: T) {}

reuse to_reuse as bar;
// desugaring:
fn bar<T: Clone>(x: T) {
  to_reuse(x)
}
```

Generics, predicates and signature are simply copied. Generic arguments in paths are ignored during generics inheritance:

```rust
fn to_reuse<T: Clone>(_: T) {}

reuse to_reuse::<u8> as bar;
// desugaring:
fn bar<T: Clone>(x: T) {
  to_reuse::<u8>(x) // ERROR: mismatched types
}
```

Due to implementation limitations callee path is lowered without modifications. Therefore, it is a compilation error at the moment.

#### free functions to trait methods:

```rust
trait Trait<'a, A> {
    fn foo<'b, B>(&self, x: A, y: B) {...}
}

reuse Trait::foo;
// desugaring:
fn foo<'a, 'b, This: Trait<'a, A>, A, B>(this: &This, x: A, y: B) {
  Trait::foo(this, x, y)
}
```

The inheritance is similar to the previous case but with some corrections:

- `Self` parameter converted into `T: Trait`
- generic parameters need to be reordered so that lifetimes go first

Arguments are similarly ignored.

---

In the future, we plan to  support generic inheritance for delegating from all contexts to all contexts (from free/trait/impl to free/trait /impl). These cases were considered first as the simplest from the implementation perspective.
2024-07-30 10:39:33 +00:00
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