Rollup of 10 pull requests
Successful merges:
- #118833 (Add lint against function pointer comparisons)
- #122161 (Fix suggestion when shorthand `self` has erroneous type)
- #133233 (Add context to "const in pattern" errors)
- #133761 (Update books)
- #133843 (Do not emit empty suggestion)
- #133863 (Rename `core_pattern_type` and `core_pattern_types` lib feature gates to `pattern_type_macro`)
- #133872 (No need to create placeholders for GAT args in confirm_object_candidate)
- #133874 (`fn_sig_for_fn_abi` should return a `ty::FnSig`, no need for a binder)
- #133890 (Add a new test ui/incoherent-inherent-impls/no-other-unrelated-errors to check E0116 does not cause unrelated errors)
- #133892 (Revert #133817)
r? `@ghost`
`@rustbot` modify labels: rollup
Add a new test ui/incoherent-inherent-impls/no-other-unrelated-errors to check E0116 does not cause unrelated errors
rustc xxx (we do not know) to 1.82.0 emits unrelated errors when E0116 is present (see #125814).
We do not know what caused and fixed it, but add a test to confirm rustc does not cause the same error in the future.
Rename `core_pattern_type` and `core_pattern_types` lib feature gates to `pattern_type_macro`
That's what the gates are actually gating, and the single char difference in naming was not helpful either
fixes#128987
Do not emit empty suggestion
The `println!();` statement's span doesn't include the `;`, and the modified suggestions where trying to get the `;` by getting the differenece between the statement's and the expression's spans, which was an empty suggestion.
Fix#133833, fix#133834.
Add context to "const in pattern" errors
*Each commit addresses specific diagnostics.*
- Add primary span labels
- Point at `const` item, and `const` generic param definition
- Reword messages and notes
- Point at generic param through which an associated `const` is being referenced
- Silence const in pattern with evaluation errors when they come from `const` items that already emit a diagnostic
- On non-structural type in const used as pattern, point at the type that should derive `PartialEq`
Add lint against function pointer comparisons
This is kind of a follow-up to https://github.com/rust-lang/rust/pull/117758 where we added a lint against wide pointer comparisons for being ambiguous and unreliable; well function pointer comparisons are also unreliable. We should IMO follow a similar logic and warn people about it.
-----
## `unpredictable_function_pointer_comparisons`
*warn-by-default*
The `unpredictable_function_pointer_comparisons` lint checks comparison of function pointer as the operands.
### Example
```rust
fn foo() {}
let a = foo as fn();
let _ = a == foo;
```
### Explanation
Function pointers comparisons do not produce meaningful result since they are never guaranteed to be unique and could vary between different code generation units. Furthermore different function could have the same address after being merged together.
----
This PR also uplift the very similar `clippy::fn_address_comparisons` lint, which only linted on if one of the operand was an `ty::FnDef` while this PR lints proposes to lint on all `ty::FnPtr` and `ty::FnDef`.
```@rustbot``` labels +I-lang-nominated
~~Edit: Blocked on https://github.com/rust-lang/libs-team/issues/323 being accepted and it's follow-up pr~~
Make sure to record deps from cached task in new solver on first run
We weren't actually performing a read of the dep node in `with_cached_task` in the new solver, which meant that all queries that computed a goal for the first time were just not recording the query dependencies that we call in that query.
In the incremental test, the typeck query for `fn poll` isn't being marked red even tho it's invalidated due to its writeback results changing. This happens b/c we normalize `Self::Error` into `Error`, which should call `type_of` which is a red query (since `ty::Adt` contains an `AdtDef`, and that `AdtDef`'s stable hash changes since it's ). However, since we weren't tracking deps in that normalize query, the typeck result was remaining green, and we were trying to decode a def id that no longer exists (the field that got removed).
r? lcnr
rustc xxx (we do not know) to 1.82.0 emits unrelated errors when E0116
is present (see #125814).
We do not know what caused and fixed it, but add a test to confirm rustc
does not cause the same error in the future.
Point at types that need to be marked with `#[derive(PartialEq)]`.
We use a visitor to look at a type that isn't structural, looking for all ADTs that don't derive `PartialEq`. These can either be manual `impl PartialEq`s or no `impl` at all, so we differentiate between those two cases to provide more context to the user. We also only point at types and impls from the local crate, otherwise show only a note.
```
error: constant of non-structural type `&[B]` in a pattern
--> $DIR/issue-61188-match-slice-forbidden-without-eq.rs:15:9
|
LL | struct B(i32);
| -------- must be annotated with `#[derive(PartialEq)]` to be usable in patterns
LL |
LL | const A: &[B] = &[];
| ------------- constant defined here
...
LL | A => (),
| ^ constant of non-structural type
|
= note: see https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html for details
```
- Point at type that should derive `PartialEq` to be structural.
- Point at manual `impl PartialEq`, explaining that it is not sufficient to be structural.
```
error: constant of non-structural type `MyType` in a pattern
--> $DIR/const-partial_eq-fallback-ice.rs:14:12
|
LL | struct MyType;
| ------------- `MyType` must be annotated with `#[derive(PartialEq)]` to be usable in patterns
...
LL | const CONSTANT: &&MyType = &&MyType;
| ------------------------ constant defined here
...
LL | if let CONSTANT = &&MyType {
| ^^^^^^^^ constant of non-structural type
|
note: the `PartialEq` trait must be derived, manual `impl`s are not sufficient; see https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html for details
--> $DIR/const-partial_eq-fallback-ice.rs:5:1
|
LL | impl PartialEq<usize> for MyType {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
```
error: trait object `dyn Send` cannot be used in patterns
--> $DIR/issue-70972-dyn-trait.rs:6:9
|
LL | const F: &'static dyn Send = &7u32;
| -------------------------- constant defined here
...
LL | F => panic!(),
| ^ trait object can't be used in patterns
```
- Add primary span labels.
- Point at const generic parameter used as pattern.
- Point at statics used as pattern.
- Point at let bindings used in const pattern.
Centralize emitting an error in `const_to_pat` so that all errors from that evaluating a `const` in a pattern can add addditional information. With this, now point at the `const` item's definition:
```
error[E0158]: constant pattern depends on a generic parameter
--> $DIR/associated-const-type-parameter-pattern.rs:20:9
|
LL | pub trait Foo {
| -------------
LL | const X: EFoo;
| ------------- constant defined here
...
LL | A::X => println!("A::X"),
| ^^^^
```
The `println!();` statement's span doesn't include the `;`, and the modified suggestions where trying to get the `;` by getting the differenece between the statement's and the expression's spans, which was an empty suggestion.
Fix#133833, fix#133834.
Avoid `opaque type not constrained` errors in the presence of other errors
pulled out of https://github.com/rust-lang/rust/pull/128440
These errors carry no new information if the opaque type was actually used in a constraining (but erroneous) way somewhere.
coverage: Use a separate counter type and simplification step during counter creation
When instrumenting a function's MIR for coverage, there is a point where we need to decide, for each node in the control-flow graph, whether its execution count will be tracked by a physical counter, or by an expression that combines physical counters from other parts of the graph.
Currently the code for doing that is heavily tied to the final form of the LLVM coverage mapping format, and performs some important simplification steps on-the-fly. These factors make the code extremely difficult to modify without breaking or massively worsening the resulting coverage-instrumentation metadata.
---
This PR aims to improve that situation somewhat by adding an extra intermediate representation between the code that chooses how each node will be counted, and the code that converts those decisions into actual tables of physical counters and trees of counter expressions.
As part of doing that, some of the simplifications that are currently performed during the main counter creation step have been pulled out into a separate step.
In most cases the resulting coverage metadata is equivalent, slightly better, or slightly worse. The biggest outlier is `counters.rs`, where the coverage metadata ends up about 10% larger. This seems to be the result of the new approach having less subexpression sharing (because it relies on flatten-sort-cancel), and therefore being less effective at taking advantage of MIR optimizations to replace counters for unused control-flow with zeroes. I think the modest downside is acceptable in light of the future possibilities opened up by this decoupling.
Don't try and handle unfed `type_of` on anon consts
The `type_of` query for anon consts in the type system is actually implemented by feeding the return value during hir ty lowering, not the hir-based logic in `const_arg_anon_type_of`. The HIR based logic is incomplete (doesn't handle all hir nodes) and also generally wrong to call (re-lowers HIR or invokes typeck which can result in query cycles).
r? `@compiler-errors`
Make CoercePointee errors translatable
Tracked by #123430
Just in case that a translatable error message would become a blocker to stabilization, this PR switches over to fluent error messages, which also slightly improve the wordings and use more accurate span information.
cc `@Darksonn` `@traviscross`
stop replacing bivariant args with `'static` when computing closure requirements
It is unnecessary, these get constrained when checking that the opaque type is well-formed.
It also results in the opaque type no longer being well formed. If you've got `fn foo<'a>() -> impl Sized + 'a` the opaque is `type Opaque<'a, 'aDummy> where 'a: 'aDummy, 'aDummy: 'a` where `'aDummy` is bivariant. If we call `foo::<'b>()` inside of a closure and its return type ends up in a type test, we start out with the WF `Opaque<'b, 'b>`, and then replace the bivariant `'b` with `'static`. `Opaque<'b, 'static>` is no longer well-formed. Given how these type tests are used, I don't think this caused any practical issues.
r? types
Fix MutVisitor's default implementations to visit Stmt's and BinOp's spans
The `Stmt` case is a bug introduced almost certainly unintentionally by https://github.com/rust-lang/rust/pull/126993. The code _used_ to visit and mutate `span` correctly, but got changed as follows by that PR. Notice how `span` is **copied** into the output by `|kind| Stmt { id, kind, span }` which happens after the mutation in the correct code (red) and before the mutation in the incorrect code (green).
```diff
pub fn noop_flat_map_stmt<T: MutVisitor>(
Stmt { kind, mut span, mut id }: Stmt,
vis: &mut T,
) -> SmallVec<[Stmt; 1]> {
vis.visit_id(&mut id);
- vis.visit_span(&mut span);
let stmts: SmallVec<_> = noop_flat_map_stmt_kind(kind, vis)
.into_iter()
.map(|kind| Stmt { id, kind, span })
.collect();
if stmts.len() > 1 {
panic!(...);
}
+ vis.visit_span(&mut span);
stmts
}
```
Update `NonZero` and `NonNull` to not field-project (per MCP#807)
https://github.com/rust-lang/compiler-team/issues/807#issuecomment-2506098540 was accepted, so this is the first PR towards moving the library to not using field projections into `[rustc_layout_scalar_valid_range_*]` types.
`NonZero` was already using `transmute` nearly everywhere, so there are very few changes to it.
`NonNull` needed more changes, but they're mostly simple, changing `.pointer` to `.as_ptr()`.
r? libs
cc #133324, which will tidy up some of the MIR from this a bit more, but isn't a blocker.
Remove `generic_associated_types_extended` feature gate
This PR retires nightly support for the `generic_associated_types_extended` feature. This feature hasn't received much attention in the last two years or so, and I believe the feature still remains both unsound and ICEy to use. I think that if we were to redesign and reimplement it, we'd want to first figure out how to implement it soundly, but in the mean time I'd prefer to clean this up.
r? ``@lcnr`` cc ``@jackh726`` who added this feature gate I think
improve TagEncoding::Niche docs, sanity check, and UB checks
Turns out the `niche_variants` range can actually contain the `untagged_variant`. We should report this as UB in Miri, so this PR implements that.
Also rename `partially_check_layout` to `layout_sanity_check` for better consistency with how similar functions are called in other parts of the compiler.
Turns out my adjustments to the transmutation logic also fix https://github.com/rust-lang/rust/issues/126267.