This version is a squash-rebased version of a series
of exiermental commits, since large parts of them
were broken out into PR #125069.
It explicitly handles universe violations in higher-kinded
outlives constraints by adding extra outlives static constraints.
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#119717Fixes#123664Fixes#124857Fixes#126148
Rename `super_predicates_of` and similar queries to `explicit_*` to note that they're not elaborated
Rename:
* `super_predicates_of` -> `explicit_super_predicates_of`
* `implied_predicates_of` -> `explicit_implied_predicates_of`
* `supertraits_containing_assoc_item` -> `explicit_supertraits_containing_assoc_item`
This makes it clearer that, unlike (for example) [`TyCtxt::super_traits_of`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.TyCtxt.html#method.super_traits_of), we don't automatically elaborate this set of predicates.
r? ``@lcnr`` or ``@oli-obk`` or someone from t-types idc
patchable-function-entry: Add unstable compiler flag and attribute
Tracking issue: #123115
Add the -Z patchable-function-entry compiler flag and the #[patchable_function_entry(prefix_nops = m, entry_nops = n)] attribute.
Rebased and adjusted the canditate implementation to match changes in the RFC.
coverage: Make `#[coverage(..)]` apply recursively to nested functions
This PR makes the (currently-unstable) `#[coverage(off)]` and `#[coverage(on)]` attributes apply recursively to all nested functions/closures, instead of just the function they are directly attached to.
Those attributes can now also be applied to modules and to impl/impl-trait blocks, where they have no direct effect, but will be inherited by all enclosed functions/closures/methods that don't override the inherited value.
---
Fixes#126625.
Remove more `PtrToPtr` casts in GVN
This addresses two things I noticed in MIR:
1. `NonNull::<T>::eq` does `(a as *mut T) == (b as *mut T)`, but it could just compare the `*const T`s, so this removes `PtrToPtr` casts that are on both sides of a pointer comparison, so long as they're not fat-to-thin casts.
2. `NonNull::<T>::addr` does `transmute::<_, usize>(p as *const ())`, but so long as `T: Thin` that cast doesn't do anything, and thus we can directly transmute the `*const T` instead.
r? mir-opt
`-Z patchable-function-entry` works like `-fpatchable-function-entry`
on clang/gcc. The arguments are total nop count and function offset.
See MCP rust-lang/compiler-team#704
transmute size check: properly account for alignment
Fixes another place where ZST alignment was ignored when checking whether something is a newtype. I wonder how many more of these there are...
Fixes https://github.com/rust-lang/rust/issues/101084
Add `SliceLike` to `rustc_type_ir`, use it in the generic solver code (+ some other changes)
First, we split out `TraitRef::new_from_args` which takes *just* `ty::GenericArgsRef` from `TraitRef::new` which takes `impl IntoIterator<Item: Into<GenericArg>>`. I will explain in a minute why.
Second, we introduce `SliceLike`, which allows us to be generic over `List<T>` and `[T]`. This trait has an `as_slice()` and `into_iter()` method, and some other convenience functions. However, importantly, since types like `I::GenericArgs` now implement `SliceLike` rather than `IntoIter<Item = I::GenericArg>`, we can't use `TraitRef::new` on this directly. That's where `new_from_args` comes in.
Finally, we adjust all the code to use these slice operators. Some things get simpler, some things get a bit more annoying since we need to use `as_slice()` in a few places. 🤷
r? lcnr
Save 2 pointers in `TerminatorKind` (96 → 80 bytes)
These things don't need to be `Vec`s; boxed slices are enough.
The frequent one here is call arguments, but MIR building knows the number of arguments from the THIR, so the collect is always getting the allocation right in the first place, and thus this shouldn't ever add the shrink-in-place overhead.
This section of code depends on `rustc_apfloat` rather than our internal
types, so this is one potential ICE that we should be able to melt now.
This also fixes some missing range and match handling in `rustc_middle`.
These things don't need to be `Vec`s; boxed slices are enough.
The frequent one here is call arguments, but MIR building knows the number of arguments from the THIR, so the collect is always getting the allocation right in the first place, and thus this shouldn't ever add the shrink-in-place overhead.
`PtrMetadata` doesn't care about `*const`/`*mut`/`&`/`&mut`, so GVN away those casts in its argument.
This includes updating MIR to allow calling PtrMetadata on references too, not just raw pointers. That means that `[T]::len` can be just `_0 = PtrMetadata(_1)`, for example.
# Conflicts:
# tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-abort.mir
# tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-unwind.mir
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``
Stabilise `c_unwind`
Fix#74990Fix#115285 (that's also where FCP is happening)
Marking as draft PR for now due to `compiler_builtins` issues
r? `@Amanieu`
Trying to address an incremental compilation issues
This pull request contains two independent changes, one makes it so when `try_force_from_dep_node` fails to recover a query - it marks the node as "red" instead of "green" and the second one makes Debug impl for `DepNode` less panicky if it encounters something from the previous compilation that doesn't map to anything in the current one.
I'm not 100% confident that this is the correct approach, but so far I managed to find a bunch of comments suggesting that some things are allowed to fail in a certain way and changes I made are allowing for those things to fail this way and it fixes all the small reproducers I managed to find.
Compilation panic this pull request avoids is caused by an automatically generated code on an associated type and it is not happening if something else marks it as outdated first (or close like that, but scenario is quite obscure).
Fixes https://github.com/rust-lang/rust/issues/107226
Fixes https://github.com/rust-lang/rust/issues/125367
Most modules have such a blank line, but some don't. Inserting the blank
line makes it clearer that the `//!` comments are describing the entire
module, rather than the `use` declaration(s) that immediately follows.
This makes their intent and expected location clearer. We see some
examples where these comments were not clearly separate from `use`
declarations, which made it hard to understand what the comment is
describing.
Apparently MIR borrowck cares about at least one of these for checking variance.
In runtime MIR, though, there's no need for them as `PtrToPtr` does the same thing.
(Banning them simplifies passes like GVN that no longer need to handle multiple cast possibilities.)
local_def_path_hash_to_def_id is used by Debug impl for DepNode and it
looks for DefPathHash inside the current compilation. During incremental
compilation we are going through nodes that belong to a previous
compilation and might not be present and a simple attempt to print such
node with tracing::debug (try_mark_parent_green does it for example)
results in a otherwise avoidable panic
Panic was added in https://github.com/rust-lang/rust/pull/82183,
specifically in 2b60338ee9, with a comment "We only use this mapping for
cases where we know that it must succeed.", but I'm not sure if this
property holds when we traverse nodes from the old compilation in order
to figure out if they are valid or not
Rollup of 6 pull requests
Successful merges:
- #125447 (Allow constraining opaque types during subtyping in the trait system)
- #125766 (MCDC Coverage: instrument last boolean RHS operands from condition coverage)
- #125880 (Remove `src/tools/rust-demangler`)
- #126154 (StorageLive: refresh storage (instead of UB) when local is already live)
- #126572 (override user defined channel when using precompiled rustc)
- #126662 (Unconditionally warn on usage of `wasm32-wasi`)
r? `@ghost`
`@rustbot` modify labels: rollup
Make pretty printing for `f16` and `f128` consistent
Currently the docs show e.g.
{transmute(0xfffeffffffffffffffffffffffffffff): f128}
for f128 constants. This should fix that to instead use apfloat for printing, as is done for `f32` and `f64`.
Currently the docs show e.g.
{transmute(0xfffeffffffffffffffffffffffffffff): f128}
for f128 constants. This should fix that to instead use apfloat for
printing, as is done for `f32` and `f64`.
Uplift next trait solver to `rustc_next_trait_solver`
🎉
There's so many FIXMEs! Sorry! Ideally this merges with the FIXMEs and we track and squash them over the near future.
Also, this still doesn't build on anything other than rustc. I still need to fix `feature = "nightly"` in `rustc_type_ir`, and remove and fix all the nightly feature usage in the new trait solver (notably: let-chains).
Also, sorry `@lcnr` I know you asked for me to separate the commit where we `mv rustc_trait_selection/solve/... rustc_next_trait_solver/solve/...`, but I had already done all the work by that point. Luckily, `git` understands the file moves so it should still be relatively reviewable.
If this is still very difficult to review, then I can do some rebasing magic to try to separate this out. Please let me know!
r? lcnr
Replace all `&DiagCtxt` with a `DiagCtxtHandle<'_>` wrapper type
r? `@davidtwco`
This paves the way for tracking more state (e.g. error tainting) in the diagnostic context handle
Basically I will add a field to the `DiagCtxtHandle` that refers back to the `InferCtxt`'s (and others) `Option<ErrorHandled>`, allowing us to immediately taint these contexts when emitting an error and not needing manual tainting anymore (which is easy to forget and we don't do in general anyway)
Rename `InstanceDef` -> `InstanceKind`
Renames `InstanceDef` to `InstanceKind`. The `Def` here is confusing, and makes it hard to distinguish `Instance` and `InstanceDef`. `InstanceKind` makes this more obvious, since it's really just describing what *kind* of instance we have.
Not sure if this is large enough to warrant a types team MCP -- it's only 53 files. I don't personally think it does, but happy to write one if anyone disagrees. cc ``@rust-lang/types``
r? types
Only compute vtable information during codegen
This PR removes vtable information from the `Object` and `TraitUpcasting` candidate sources in the trait solvers, and defers the computation of relevant information to `Instance::resolve`. This is because vtables really aren't a thing in the trait world -- they're an implementation detail in codegen.
Previously it was just easiest to tangle this information together since we were already doing the work of looking at all the supertraits in the trait solver, and specifically because we use traits to represent when it's possible to call a method via a vtable (`Object` candidate) and do upcasting (`Unsize` candidate). but I am somewhat suspicious we're doing a *lot* of extra work, especially in polymorphic contexts, so let's see what perf says.
smir: merge identical Constant and ConstOperand types
The first commit renames the const operand visitor functions on regular MIR to match the type name, that was forgotten in the original rename.
The second commit changes stable MIR, fixing https://github.com/rust-lang/project-stable-mir/issues/71. Previously there were two different smir types for the MIR type `ConstOperand`, one used in `Operand` and one in `VarDebugInfoContents`.
Maybe we should have done this with https://github.com/rust-lang/rust/pull/125967, so there's only a single breaking change... but I saw that PR too late.
Fixes https://github.com/rust-lang/project-stable-mir/issues/71
Rollup of 9 pull requests
Successful merges:
- #125829 (rustc_span: Add conveniences for working with span formats)
- #126361 (Unify intrinsics body handling in StableMIR)
- #126417 (Add `f16` and `f128` inline ASM support for `x86` and `x86-64`)
- #126424 ( Also sort `crt-static` in `--print target-features` output)
- #126428 (Polish `std::path::absolute` documentation.)
- #126429 (Add `f16` and `f128` const eval for binary and unary operationations)
- #126448 (End support for Python 3.8 in tidy)
- #126488 (Use `std::path::absolute` in bootstrap)
- #126511 (.mailmap: Associate both my work and my private email with me)
r? `@ghost`
`@rustbot` modify labels: rollup
Add `f16` and `f128` const eval for binary and unary operationations
Add const evaluation and Miri support for f16 and f128, including unary and binary operations. Casts are not yet included.
Fixes https://github.com/rust-lang/rust/issues/124583
r? ``@RalfJung``
Use `Variance` glob imported variants everywhere
Fully commit to using the globbed variance. Could be convinced the other way, and change this PR to not use the globbed variants anywhere, but I'd rather we do one or the other.
r? lcnr
change method resolution to constrain hidden types instead of rejecting method candidates
Some of these are in probes and may affect inference. This is therefore a breaking change.
This allows new code to compile on stable:
```rust
trait Trait {}
impl Trait for u32 {}
struct Bar<T>(T);
impl Bar<u32> {
fn foo(self) {}
}
fn foo(x: bool) -> Bar<impl Sized> {
if x {
let x = foo(false);
x.foo();
//^ this used to not find the `foo` method, because while we did equate `x`'s type with possible candidates, we didn't allow opaque type inference while doing so
}
todo!()
}
```
r? ```````@compiler-errors```````
fixes #121404
cc https://github.com/rust-lang/rust/issues/116652
Remove `DebugWithInfcx` machinery
This PR removes `DebugWithInfcx` after having a lot of second thoughts about it due to recent type system uplifting work. We could add it back later if we want, but I don't think the amount of boilerplate in the complier and the existence of (kindof) hacks like `NoInfcx` currently justify the existence of `DebugWithInfcx`, especially since it's not even being used anywhere in the compiler currently.
The motivation for `DebugWithInfcx` is that we want to be able to print infcx-aware information, such as universe information[^1] (though if there are other usages that I'm overlooking, please let me know). I think there are probably more tailored solutions that can specifically be employed in places where this infcx-aware printing is necessary. For example, one way of achieving this is by implementing a custom `FmtPrinter` which overloads `ty_infer_name` (perhaps also extending it to have overrideable stubs for printing placeholders too) to print the `?u.i` name for an infer var. This will necessitate uplifting `Print` from `rustc_middle::ty::print`, but this seems a bit more extensible and reusable than `DebugWithInfcx`.
One of the problems w/ `DebugWithInfcx` is its opt-in-ness. Even if a compiler dev adds a new `debug!(ty)` in a context where there is an `infcx` we can access, they have to *opt-in* to using `DebugWithInfcx` with something like `debug!(infcx.with(ty))`. This feels to me like it risks a lot of boilerplate, and very easy to just forget adding it at all, especially in cases like `#[instrument]`.
A second problem is the `NoInfcx` type itself. It's necessary to have this dummy infcx implementation since we often want to print types outside of the scope of a valid `Infcx`. Right now, `NoInfcx` is only *partially* a valid implementation of `InferCtxtLike`, except for the methods that we specifically need for `DebugWithInfcx`. As I work on uplifting the trait solver, I actually want to add a lot more methods to `InferCtxtLike` and having to add `unreachable!("this should never be called")` stubs for uplifted methods like `next_ty_var` is quite annoying.
In reality, I actually only *really* care about the second problem -- we could, perhaps, instead just try to get rid of `NoInfcx` and just just duplicate `Debug` and `DebugWithInfcx` for most types. If we're okay with duplicating all these implementations (though most of them would just be trivial `#[derive(Debug, DebugWithInfcx)]`), I'd be okay with that too 🤔
r? `@BoxyUwU` `@lcnr` would like to know your thoughts -- happy to discuss this further, mainly trying to bring this problem up
[^1]: Which in my experience is only really necessary when we're debugging things like generalizer bugs.
interpret: ensure we check bool/char for validity when they are used in a cast
In general, `Scalar::to_bits` is a bit dangerous as it bypasses all type information. We should usually prefer matching on the type and acting according to that. So I also refactored `unary_op` handling of integers to do that. The remaining `to_bits` uses are operations that just fundamentally don't care about the sign (and only work on integers).
invalid_char_cast.rs is the key new test, the others already passed before this PR.
r? `@oli-obk`
Only compute `specializes` query if (min)specialization is enabled in the crate of the specializing impl
Fixes (after backport) https://github.com/rust-lang/rust/issues/125197
### What
https://github.com/rust-lang/rust/pull/122791 makes it so that inductive cycles are no longer hard errors. That means that when we are testing, for example, whether these impls overlap:
```rust
impl PartialEq<Self> for AnyId {
fn eq(&self, _: &Self) -> bool {
todo!()
}
}
impl<T: Identifier> PartialEq<T> for AnyId {
fn eq(&self, _: &T) -> bool {
todo!()
}
}
```
...given...
```rust
pub trait Identifier: Display + 'static {}
impl<T> Identifier for T where T: PartialEq + Display + 'static {}
```
Then we try to see if the second impl holds given `T = AnyId`. That requires `AnyId: Identifier`, which requires that `AnyId: PartialEq`, which is satisfied by these two impl candidates... The `PartialEq<T>` impl is a cycle, and we used to winnow it when we used to treat inductive cycles as errors.
However, now that we don't winnow it, this means that we *now* try calling `candidate_should_be_dropped_in_favor_of`, which tries to check whether one of the impls specializes the other: the `specializes` query. In that query, we currently bail early if the impl is local.
However, in a foreign crate, we try to compute if the two impls specialize each other by doing trait solving. This may itself lead to the same situation where we call `specializes`, which will lead to a query cycle.
### How does this fix the problem
We now record whether specialization is enabled in foreign crates, and extend this early-return behavior to foreign impls too. This means that we can only encounter these cycles if we truly have a specializing impl from a crate with specialization enabled.
-----
r? `@oli-obk` or `@lcnr`
offset_of: allow (unstably) taking the offset of slice tail fields
Fields of type `[T]` have a statically known offset, so there is no reason to forbid them in `offset_of!`. This PR adds the `offset_of_slice` feature to allow them.
I created a tracking issue: https://github.com/rust-lang/rust/issues/126151.
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`
Remove the `ty` field from type system `Const`s
Fixes#125556Fixes#122908
Part of the work on `adt_const_params`/`generic_const_param_types`/`min_generic_const_exprs`/generally making the compiler nicer. cc rust-lang/project-const-generics#44
Please review commit-by-commit otherwise I wasted a lot of time not just squashing this into a giant mess (and also it'll be SO much nicer because theres a lot of fluff changes mixed in with other more careful changes if looking via File Changes
---
Why do this?
- The `ty` field keeps causing ICEs and weird behaviour due to it either being treated as "part of the const" or it being forgotten about leading to ICEs.
- As we move forward with `adt_const_params` and a potential `min_generic_const_exprs` it's going to become more complex to actually lower the correct `Ty<'tcx>`
- It muddles the idea behind how we check `Const` arguments have the correct type. By having the `ty` field it may seem like we ought to be relating it when we relate two types, or that its generally important information about the `Const`.
- Brings the compiler more in line with `a-mir-formality` as that also tracks the type of type system `Const`s via `ConstArgHasType` bounds in the env instead of on the `Const` itself.
- A lot of stuff is a lot nicer when you dont have to pass around the type of a const lol. Everywhere we construct `Const` is now significantly nicer 😅
See #125671's description for some more information about the `ty` field
---
General summary of changes in this PR:
- Add `Ty` to `ConstKind::Value` as otherwise there is no way to implement `ConstArgHasType` to ensure that const arguments are correctly typed for the parameter when we stop creating anon consts for all const args. It's also just incredibly difficult/annoying to thread the correct `Ty` around to a bunch of ctfe functions otherwise.
- Fully implement `ConstArgHasType` in both the old and new solver. Since it now has no reliance on the `ty` field it serves its originally intended purpose of being able to act as a double check that trait vs impls have correctly typed const parameters. It also will now be able to be responsible for checking types of const arguments to parameters under `min_generic_const_exprs`.
- Add `Ty` to `mir::Const::Ty`. I dont have a great understanding of why mir constants are setup like this to be honest. Regardless they need to be able to determine the type of the const and the easiest way to make this happen was to simply store the `Ty` along side the `ty::Const`. Maybe we can do better here in the future but I'd have to spend way more time looking at everywhere we use `mir::Const`.
- rustdoc has its own `Const` which also has a `ty` field. It was relatively easy to remove this.
---
r? `@lcnr` `@compiler-errors`
Don't walk the bodies of free constants for reachability.
follow-up to #122371
cc #119214
This avoids codegening items (e.g. functions) that are only used during const eval, but do not reach their final constant value (e.g. via function pointers).
r? `@tmiasko`
Add intra-doc-links to rustc_middle crate-level docs.
Makes it slightly faster to find these modules, as you don't need to hunt for them in the big list.
Add `size_of` and `size_of_val` and `align_of` and `align_of_val` to the prelude
(Note: need to update the PR to add `align_of` and `align_of_val`, and remove the second commit with the myriad changes to appease the lint.)
Many, many projects use `size_of` to get the size of a type. However,
it's also often equally easy to hardcode a size (e.g. `8` instead of
`size_of::<u64>()`). Minimizing friction in the use of `size_of` helps
ensure that people use it and make code more self-documenting.
The name `size_of` is unambiguous: the name alone, without any prefix or
path, is self-explanatory and unmistakeable for any other functionality.
Adding it to the prelude cannot produce any name conflicts, as any local
definition will silently shadow the one from the prelude. Thus, we don't
need to wait for a new edition prelude to add it.
Store the types of `ty::Expr` arguments in the `ty::Expr`
Part of #125958
In attempting to remove the `ty` field on `Const` it will become necessary to store the `Ty<'tcx>` inside of `Expr<'tcx>`. In order to do this without blowing up the size of `ConstKind`, we start storing the type/const args as `GenericArgs`
r? `@oli-obk`
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
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) {
| ++++++
```
Uplift `{Closure,Coroutine,CoroutineClosure}Args` and friends to `rustc_type_ir`
Part of converting the new solver's `structural_traits.rs` to be interner-agnostic.
I decided against aliasing `ClosureArgs<TyCtxt<'tcx>>` to `ClosureArgs<'tcx>` because it seemed so rare. I could do so if desired, though.
r? lcnr
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%.
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
coverage: Rename MC/DC `conditions_num` to `num_conditions`
Updated version of #124571, without the other changes that were split out into #125108 and #125700.
This value represents a quantity of conditions, not an ID, so the new spelling is more appropriate.
Some of the code touched by this PR could perhaps use some other changes, but I would prefer to keep this PR as a simple renaming and avoid scope creep.
`@rustbot` label +A-code-coverage
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) {
| ++++++
```
Omit non-needs_drop drop_in_place in vtables
This replaces the drop_in_place reference with null in vtables. On librustc_driver.so, this drops about ~17k (11%) dynamic relocations from the output, since many vtables can now be placed in read-only memory, rather than having a relocated pointer included.
This makes a tradeoff by adding a null check at vtable call sites. I'm not sure that's readily avoidable without changing the vtable format (e.g., so that we can use a pc-relative relocation instead of an absolute address, and avoid the dynamic relocation that way). But it seems likely that the check is cheap at runtime.
Accepted MCP: https://github.com/rust-lang/compiler-team/issues/730
This replaces the drop_in_place reference with null in vtables. On
librustc_driver.so, this drops about ~17k dynamic relocations from the
output, since many vtables can now be placed in read-only memory, rather
than having a relocated pointer included.
This makes a tradeoff by adding a null check at vtable call sites.
That's hard to avoid without changing the vtable format (e.g., to use a
pc-relative relocation instead of an absolute address, and avoid the
dynamic relocation that way). But it seems likely that the check is
cheap at runtime.
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
[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.
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)
remove proof tree formatting, make em shallow
Debugging via tracing `RUSTC_LOG=rustc_trait_selection::solve=debug` is now imo slightly more readable then the actual proof tree formatter. Removing everything that's not needed for the `analyse` visitor allows us to remove a bunch of code.
I personally believe that we should continue to use tracing over proof trees for debugging:
- it eagerly prints, allowing us to debug ICEs
- the proof tree builder ends up going out of sync with the actual runtime behavior, which is confusing
- using shallow proof trees is a lot more performant as we frequently do not recurse into all nested goals when using an analyse visitor
- this allows us to clean up the implementation and remove some code
r? ```@compiler-errors```
Fail relating constants of different types
fixes#121585fixes#121858fixes#124151
I gave this several attempts before, but we lost too many important diagnostics until I managed to make compilation never bail out early. We have reached this point, so now we can finally fix all those ICEs by bubbling up an error instead of continueing when we encounter a bug.
Warn (or error) when `Self` ctor from outer item is referenced in inner nested item
This implements a warning `SELF_CONSTRUCTOR_FROM_OUTER_ITEM` when a self constructor from an outer impl is referenced in an inner nested item. This is a proper fix mentioned https://github.com/rust-lang/rust/pull/117246#discussion_r1374648388.
This warning is additionally bumped to a hard error when the self type references generic parameters, since it's almost always going to ICE, and is basically *never* correct to do.
This also reverts part of https://github.com/rust-lang/rust/pull/117246, since I believe this is the proper fix and we shouldn't need the helper functions (`opt_param_at`/`opt_type_param`) any longer, since they shouldn't really ever be used in cases where we don't have this problem.
Remove more `#[macro_use] extern crate tracing`
Because explicit importing of macros via use items is nicer (more standard and readable) than implicit importing via `#[macro_use]`. Continuing the work from #124511 and #124914.
r? `@jackh726`
With the removal of `LintDiagnostic::msg` / the `msg` param from
lint diag APIs, primary messages for lint diags are always constructed
lazily inside decorator fns rendering this wrapper type unused / useless.
* 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
Rollup of 7 pull requests
Successful merges:
- #125043 (reference type safety invariant docs: clarification)
- #125306 (Force the inner coroutine of an async closure to `move` if the outer closure is `move` and `FnOnce`)
- #125355 (Use Backtrace::force_capture instead of Backtrace::capture in rustc_log)
- #125382 (rustdoc: rename `issue-\d+.rs` tests to have meaningful names (part 7))
- #125391 (Minor serialize/span tweaks)
- #125395 (Remove unnecessary `.md` from the documentation sidebar)
- #125399 (Stop using `to_hir_binop` in codegen)
r? `@ghost`
`@rustbot` modify labels: rollup
Stop using `to_hir_binop` in codegen
This came up in https://github.com/rust-lang/rust/pull/125359#discussion_r1609401311 , and looking into it we can just use the `mir::BinOp`s directly instead of `hir::BinOpKind`s.
(AKA rather than going `mir::BinOp` → `hir::BinOpKind` → `IntPredicate`, just go `mir::BinOp` → `IntPredicate`.)
An async closure may implement `FnMut`/`Fn` if it has no self-borrows
There's no reason that async closures may not implement `FnMut` or `Fn` if they don't actually borrow anything with the closure's env lifetime. Specifically, #123660 made it so that we don't always need to borrow captures from the closure's env.
See the doc comment on `should_reborrow_from_env_of_parent_coroutine_closure`:
c00957a3e2/compiler/rustc_hir_typeck/src/upvar.rs (L1777-L1823)
If there are no such borrows, then we are free to implement `FnMut` and `Fn` as permitted by our closure's inferred `ClosureKind`.
As far as I can tell, this change makes `async || {}` work in precisely the set of places they used to work before #120361.
Fixes#125247.
r? oli-obk
Add a footer in FileEncoder and check for it in MemDecoder
We have a few reports of ICEs due to decoding failures, where the fault does not lie with the compiler. The goal of this PR is to add some very lightweight and on-by-default validation to the compiler's outputs. If validation fails, we emit a fatal error for rmeta files in general that mentions the path that didn't load, and for incremental compilation artifacts we emit a verbose warning that tries to explain the situation and treat the artifacts as outdated.
The validation currently implemented here is very crude, and yet I think we have 11 ICE reports currently open (you can find them by searching issues for `1002111927320821928687967599834759150`) which this simple validation would have detected. The structure of the code changes here should permit the addition of further validation code, such as a checksum, if it is merited. I would like to have code to detect corruption such as reported in https://github.com/rust-lang/rust/issues/124719, but I'm not yet sure how to do that efficiently, and this PR is already a good size.
The ICE reports I have in mind that this PR would have smoothed over are:
https://github.com/rust-lang/rust/issues/124469https://github.com/rust-lang/rust/issues/123352https://github.com/rust-lang/rust/issues/123376 [^1]
https://github.com/rust-lang/rust/issues/99763https://github.com/rust-lang/rust/issues/93900.
---
[^1]: This one might be a compiler bug, but even if it is I think the workflow described is pushing the envelope of what we can support. This issue is one of the reasons this warning still asks people to file an issue.
Move `#[do_not_recommend]` to the `#[diagnostic]` namespace
This commit moves the `#[do_not_recommend]` attribute to the `#[diagnostic]` namespace. It still requires
`#![feature(do_not_recommend)]` to work.
r? `@compiler-errors`
Translation of the lint message happens when the actual diagnostic is
created, not when the lint is buffered. Generating the message from
BuiltinLintDiag ensures that all required data to construct the message
is preserved in the LintBuffer, eventually allowing the messages to be
moved to fluent.
Remove the `msg` field from BufferedEarlyLint, it is either generated
from the data in the BuiltinLintDiag or stored inside
BuiltinLintDiag::Normal.
Add `IntoIterator` for `Box<[T]>` + edition 2024-specific lints
* Adds a similar method probe opt-out mechanism to the `[T;N]: IntoIterator` implementation for edition 2021.
* Adjusts the relevant lints (shadowed `.into_iter()` calls, new source of method ambiguity).
* Adds some tests.
* Took the liberty to rework the logic in the `ARRAY_INTO_ITER` lint, since it was kind of confusing.
Based mostly off of #116607.
ACP: rust-lang/libs-team#263
References #59878
Tracking for Rust 2024: https://github.com/rust-lang/rust/issues/123759
Crater run was done here: https://github.com/rust-lang/rust/pull/116607#issuecomment-1770293013
Consensus afaict was that there is too much breakage, so let's do this in an edition-dependent way much like `[T; N]: IntoIterator`.
Follow-up fixes to `report_return_mismatched_types`
Some renames, simplifications, fixes, etc. Follow-ups to #123804. I don't think it totally disentangles this code, but it does remove some of the worst offenders on the "I am so confused" scale (e.g. `get_node_fn_decl`).
Uplift `RegionVid`, `TermKind` to `rustc_type_ir`, and `EagerResolver` to `rustc_next_trait_solver`
- Uplift `RegionVid`. This was complicated due to the fact that we implement `polonius_engine::Atom` for `RegionVid` -- but I just separated that into `PoloniusRegionVid`, and added `From`/`Into` impls so it can be defined in `rustc_borrowck` separately. Coherence 😵
- Change `InferCtxtLike` to expose `opportunistically_resolve_{ty,ct,lt,int,float}_var` so that we can uplift `EagerResolver` for use in the canonicalization methods.
- Uplift `TermKind` much like `GenericArgKind`
All of this is miscellaneous dependencies for making more `EvalCtxt` methods generic.
coverage: Memoize and simplify counter expressions
When creating coverage counter expressions as part of coverage instrumentation, we often end up creating obviously-redundant expressions like `c1 + (c0 - c1)`, which is equivalent to just `c0`.
To avoid doing so, this PR checks when we would create an expression matching one of 5 patterns, and uses the simplified form instead:
- `(a - b) + b` → `a`.
- `(a + b) - b` → `a`.
- `(a + b) - a` → `b`.
- `a + (b - a)` → `b`.
- `a - (a - b)` → `b`.
Of all the different ways to combine 3 operands and 2 operators, these are the patterns that allow simplification.
(Some of those patterns currently don't occur in practice, but are included anyway for completeness, to avoid having to add them later as branch coverage and MC/DC coverage support expands.)
---
This PR also adds memoization for newly-created (or newly-simplified) counter expressions, to avoid creating duplicates.
This currently makes no difference to the final mappings, but is expected to be useful for MC/DC coverage of match expressions, as proposed by https://github.com/rust-lang/rust/pull/124278#issuecomment-2106754753.
Uplift more query stuff
- Uplift various query input/response internals
- Uplift the `ProofTree` structures and make the `ProofTreeBuilder` stuff (mostly) generic over `Interner`
- Stop using `TyCtxt::def_kind` in favor of `AliasTerm::kind`
r? lcnr
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.
MIR operators: clarify Shl/Shr handling of negative offsets
"made unsigned" was not fully clear (made unsigned how? by using `abs`? no), so let's say "re-interpreted as an unsigned value of the same size" instead.
r? `@scottmcm`