Make sure we handle `backwards_incompatible_lint` drops appropriately in drop elaboration
In #131326, a new kind of scheduled drop (`drop_kind: DropKind::Value` + `backwards_incompatible_lint: true`) was added so that we could insert a new kind of no-op MIR statement (`backward incompatible drop`) for linting purposes.
These drops were intended to have *no side-effects*, but drop elaboration code forgot to handle these drops specially and they were handled otherwise as normal drops in most of the code. This ends up being **unsound** since we insert more than one drop call for some values, which means that `Drop::drop` could be called more than once.
This PR fixes this by splitting out the `DropKind::ForLint` and adjusting the code. I'm not totally certain if all of the places I've adjusted are either reachable or correct, but I'm pretty certain that it's *more* correct than it was previously.
cc `@dingxiangfei2009`
r? nikomatsakis
Fixes#134482
Do not do if ! else, use unnegated cond and swap the branches instead
I'm tidying up my ergonomic ref counting PR and I'm going to make some small, simple and unrelated changes outside that PR, so the main PR sticks more straight to the point.
Clarify the match ergonomics 2024 migration lint's output
This makes a few changes:
- Rather than using the whole pattern as a span for the lint, this collects spans for each problematic default binding mode reset and labels them with why they're problems.
- The lint's suggestions are now verbose-styled, so that it's clear what's being suggested vs. what's problematic.
- The wording is now less technical, and the hard error version of this diagnostic now links to the same reference material as the lint (currently an unwritten page of the edition guide).
I'm not totally confident in the wording or formatting, so I'd appreciate feedback on that in particular. I tried to draw a connection with word choice between the labels and the suggestion, but it might be imprecise, unclear, or cluttered. If so, it might be worth making the labels more terse and adding notes that explain them, but that's harder to read in a way too.
cc ```@Nadrieril``` ```@Jules-Bertholet```
Closes#133854. For reference, the error from that issue becomes:
```
error: pattern uses features incompatible with edition 2024
--> $DIR/remove-me.rs:6:25
|
LL | map.iter().filter(|(&(_x, _y), &_c)| false);
| ^ ^ cannot implicitly match against multiple layers of reference
| |
| cannot implicitly match against multiple layers of reference
|
help: make the implied reference pattern explicit
|
LL | map.iter().filter(|&(&(_x, _y), &_c)| false);
| +
```
`rustc_span::symbol` defines some things that are re-exported from
`rustc_span`, such as `Symbol` and `sym`. But it doesn't re-export some
closely related things such as `Ident` and `kw`. So you can do `use
rustc_span::{Symbol, sym}` but you have to do `use
rustc_span::symbol::{Ident, kw}`, which is inconsistent for no good
reason.
This commit re-exports `Ident`, `kw`, and `MacroRulesNormalizedIdent`,
and changes many `rustc_span::symbol::` qualifiers in `compiler/` to
`rustc_span::`. This is a 200+ net line of code reduction, mostly
because many files with two `use rustc_span` items can be reduced to
one.
Fix some comments related to upvars handling
I'm tidying up my ergonomic ref counting PR and I'm going to make some small, simple and unrelated changes outside that PR, so the main PR sticks more straight to the point.
Check for array lengths that aren't actually `usize`
I wish typeck wouldn't give us `ty::Array`s that have this problem in the first place, but we can check for it.
Fixes#134352
cc ``@matthiaskrgr``
rustc_mir_build: Clarify that 'mirrored' does not mean 'flipped' or 'reversed'
My intuition for 'mirrored' is that it means 'flipped' or 'reversed'. Clarify that that is not what is meant to 'mirror' the THIR from the HIR.
Make sure to use normalized ty for unevaluated const in default struct value
This cleans up the way that we construct the `mir::Const::Unevaluated` for default struct values. We were previously using `from_unevaluated`, which doesn't normalize the type, and is really only used for inline assembly. Other codepaths (such as `ExprKind::NamedConst`) use the type from the body.
Also, let's stop using `literal_operand`, which also is really not meant for calls other than for literal comparisons in pattern lowering.
Also move all of the tests to a separate subdirectory so they don't need to have the same prefix on all the test files.
Fixes#134298
r? estebank or reassign
Add some convenience helper methods on `hir::Safety`
Makes a lot of call sites simpler and should make any refactorings needed for https://github.com/rust-lang/rust/pull/134090#issuecomment-2541332415 simpler, as fewer sites have to be touched in case we end up storing some information in the variants of `hir::Safety`
Bounds-check with PtrMetadata instead of Len in MIR
Rather than emitting `Len(*_n)` in array index bounds checks, emit `PtrMetadata(copy _n)` instead -- with some asterisks for arrays and `&mut` that need it to be done slightly differently.
We're getting pretty close to removing `Len` entirely, actually. I think just one more PR after this (for slice drop shims).
r? mir
Initial implementation of `#[feature(default_field_values]`, proposed in https://github.com/rust-lang/rfcs/pull/3681.
Support default fields in enum struct variant
Allow default values in an enum struct variant definition:
```rust
pub enum Bar {
Foo {
bar: S = S,
baz: i32 = 42 + 3,
}
}
```
Allow using `..` without a base on an enum struct variant
```rust
Bar::Foo { .. }
```
`#[derive(Default)]` doesn't account for these as it is still gating `#[default]` only being allowed on unit variants.
Support `#[derive(Default)]` on enum struct variants with all defaulted fields
```rust
pub enum Bar {
#[default]
Foo {
bar: S = S,
baz: i32 = 42 + 3,
}
}
```
Check for missing fields in typeck instead of mir_build.
Expand test with `const` param case (needs `generic_const_exprs` enabled).
Properly instantiate MIR const
The following works:
```rust
struct S<A> {
a: Vec<A> = Vec::new(),
}
S::<i32> { .. }
```
Add lint for default fields that will always fail const-eval
We *allow* this to happen for API writers that might want to rely on users'
getting a compile error when using the default field, different to the error
that they would get when the field isn't default. We could change this to
*always* error instead of being a lint, if we wanted.
This will *not* catch errors for partially evaluated consts, like when the
expression relies on a const parameter.
Suggestions when encountering `Foo { .. }` without `#[feature(default_field_values)]`:
- Suggest adding a base expression if there are missing fields.
- Suggest enabling the feature if all the missing fields have optional values.
- Suggest removing `..` if there are no missing fields.
Remove a lit_to_const call
We have so many special cases of `match expr.kind { Lit() => {}, Unary(Neg, Lit()) => {} }`... I'm trying to figure out how to get these all unified, but outright removing some is good, too. So let's try it.
Tho we don't have many `const {}` blocks in the perf test suite... But I also don't know how common `const { 42 }` blocks are, I'd expect these to occur mostly from macros (like `thread_local!`)
implement checks for tail calls
Quoting the [RFC draft](https://github.com/phi-go/rfcs/blob/guaranteed-tco/text/0000-explicit-tail-calls.md):
> The argument to become is a function (or method) call, that exactly matches the function signature and calling convention of the callee. The intent is to ensure a matching ABI. Note that lifetimes may differ as long as they pass borrow checking, see [below](https://github.com/phi-go/rfcs/blob/guaranteed-tco/text/0000-explicit-tail-calls.md#return-type-coercion) for specifics on the return type.
> Tail calling closures and tail calling from closures is not allowed. This is due to the high implementation effort, see below, this restriction can be lifted by a future RFC.
> Invocations of operators were considered as valid targets but were rejected on grounds of being too error-prone. In any case, these can still be called as methods.
> Tail calling [variadic functions](https://doc.rust-lang.org/beta/unstable-book/language-features/c-variadic.html) and tail calling from variadic functions is not allowed. As support for variadic function is stabilized on a per target level, support for tail-calls regarding variadic functions would need to follow a similar approach. To avoid this complexity and to minimize implementation effort for backends, this interaction is currently not allowed but support can be added with a future RFC.
-----
The checks are implemented as a query, similarly to `check_unsafety`.
The code is cherry-picked straight out of #112657 which was written more than a year ago, so I expect we might need to change some things ^^"
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"),
| ^^^^
```