Suggest creating unary tuples when types don't match a trait
When you want to have a variadic function, a common workaround to implement this is to create a trait and then implement that trait for various tuples. For example in `pyo3` there exists
```rust
/// Calls the object with only positional arguments.
pub fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyAny> {
...
}
```
with various impls like
```rust
impl<A: IntoPy<PyObject> IntoPy<Py<PyAny>> for (A,)
impl<A: IntoPy<PyObject, B: IntoPy<PyObject> IntoPy<Py<PyAny>> for (A, B)
... etc
```
This means that if you want to call the method with a single item you have to create a unary tuple, like `(x,)`, rather than just `x`.
This PR implements a suggestion to do that, if applicable.
find the generic container rather than simply looking up for the assoc with const arg
Fixes#132534
This issue is caused by mismatched generic parameters. Previously, it tried to find `T` in `trait X`, but after this change, it will find `T` in `fn a`.
r? `@compiler-errors` as this assertion was introduced by you.
Use backticks instead of single quotes for library feature names in diagnostics
This PR changes the text of library feature errors for using unstable or body-unstable items. Displaying library feature names in backticks is consistent with other diagnostics (e.g. those from `rustc_passes`) and with the `reason`s on unstable attributes in the library. Additionally, this simplifies diagnostics when supporting multiple unstable attributes on items (see #131824) since `DiagSymbolList` also displays symbols using backticks.
This is consistent with all other diagnostics I could find containing
features and enables the use of `DiagSymbolList` for generalizing
diagnostics for unstable library features to multiple features.
Use the right span when encountering an enum variant followed by an associated item so we don't lose the associated item in the resulting code.
Do not suggest the thing twice, once as a removal of the associated item and a second time as a typo suggestion.
Added regression test for generics index out of bounds
Added a regression test for #117446
This ICE was fixed in Rust 1.75 but a regression test was never added.
This PR adds a UI test with a reduced version of the original bug report that does not rely on external crates.
Add `--print host-tuple` to print host target tuple
People often parse `-vV` output to get to the host tuple, which is annoying to do. It's easier to just get it directly.
I called it "host-tuple" instead of "host" because it's clearer that it's just the target name. I'm open to different names, but I think this one is fine.
a quick GitHub search for `'^host` reveals many instances of people doing the parsing, for example:
68e0ca57cd/README.md (L369)0e38473b0c/main.sh (L96)8a3553b865/README.md (L625)43f3ec3970/do.sh (L35)
needs a compiler FCP. I could also do an MCP but I think just an FCP here makes the most sense.
Tweak E0277 output when a candidate is available
*Follow up to #132086.*
Go from
```
error[E0277]: the trait bound `Then<Ignored<chumsky::combinator::Filter<chumsky::primitive::Any<&str, chumsky::extra::Full<EmptyErr, (), ()>>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map<impl CSTParser<'a, O>, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full<EmptyErr, (), ()>>: CSTParser<'a>` is not satisfied
--> src/main.rs:7:50
|
7 | fn leaf<'a, O>(parser: impl CSTParser<'a, O>) -> impl CSTParser<'a, ()> {
| ^^^^^^^^^^^^^^^^^^^^^^ the trait `chumsky::private::ParserSealed<'_, &str, (), chumsky::extra::Full<EmptyErr, (), ()>>` is not implemented for `Then<Ignored<Filter<Any<&str, ...>, ...>, ...>, ..., ..., ..., ...>`, which is required by `Then<Ignored<chumsky::combinator::Filter<chumsky::primitive::Any<&str, chumsky::extra::Full<EmptyErr, (), ()>>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map<impl CSTParser<'a, O>, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full<EmptyErr, (), ()>>: CSTParser<'a>`
|
= help: the trait `chumsky::private::ParserSealed<'_, &'a str, ((), ()), chumsky::extra::Full<EmptyErr, (), ()>>` is implemented for `Then<Ignored<chumsky::combinator::Filter<chumsky::primitive::Any<&str, chumsky::extra::Full<EmptyErr, (), ()>>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map<impl CSTParser<'a, O>, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full<EmptyErr, (), ()>>`
= help: for that trait implementation, expected `((), ())`, found `()`
= note: required for `Then<Ignored<Filter<Any<&str, ...>, ...>, ...>, ..., ..., ..., ...>` to implement `Parser<'_, &str, ()>`
note: required for `Then<Ignored<Filter<Any<&str, ...>, ...>, ...>, ..., ..., ..., ...>` to implement `CSTParser<'a>`
--> src/main.rs:5:16
|
5 | impl<'a, O, T> CSTParser<'a, O> for T where T: Parser<'a, &'a str, O> {}
| ^^^^^^^^^^^^^^^^ ^ ---------------------- unsatisfied trait bound introduced here
= note: the full name for the type has been written to '/home/gh-estebank/longlong/target/debug/deps/longlong-0008f9a4f2023b08.long-type-13239977239800463552.txt'
= note: consider using `--verbose` to print the full type name to the console
= note: the full name for the type has been written to '/home/gh-estebank/longlong/target/debug/deps/longlong-0008f9a4f2023b08.long-type-13239977239800463552.txt'
= note: consider using `--verbose` to print the full type name to the console
```
to
```
error[E0277]: the trait bound `Then<Ignored<chumsky::combinator::Filter<chumsky::primitive::Any<&str, chumsky::extra::Full<EmptyErr, (), ()>>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map<impl CSTParser<'a, O>, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full<EmptyErr, (), ()>>: CSTParser<'a>` is not satisfied
--> src/main.rs:7:50
|
7 | fn leaf<'a, O>(parser: impl CSTParser<'a, O>) -> impl CSTParser<'a, ()> {
| ^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound
...
11 | ws.then(parser.map(|_| ()))
| --------------------------- return type was inferred to be `Then<Ignored<..., ...>, ..., ..., ..., ...>` here
|
= help: the trait `ParserSealed<'_, &_, (), Full<_, _, _>>` is not implemented for `Then<Ignored<..., ...>, ..., ..., ..., ...>`
but trait `ParserSealed<'_, &'a _, ((), ()), Full<_, _, _>>` is implemented for it
= help: for that trait implementation, expected `((), ())`, found `()`
= note: required for `Then<Ignored<..., ...>, ..., ..., ..., ...>` to implement `Parser<'_, &str, ()>`
note: required for `Then<Ignored<..., ...>, ..., ..., ..., ...>` to implement `CSTParser<'a>`
--> src/main.rs:5:16
|
5 | impl<'a, O, T> CSTParser<'a, O> for T where T: Parser<'a, &'a str, O> {}
| ^^^^^^^^^^^^^^^^ ^ ---------------------- unsatisfied trait bound introduced here
= note: the full name for the type has been written to '/home/gh-estebank/longlong/target/debug/deps/longlong-df9d52be87eada65.long-type-1337037744507305372.txt'
= note: consider using `--verbose` to print the full type name to the console
```
* Remove redundant wording
* Introduce trait diff highlighting logic and use it
* Fix incorrect "long type written to path" logic (can be split off)
* Point at tail expression in more cases in E0277
* Avoid long primary span labels in E0277 by moving them to a `help`
Fix#132013.
There are individual commits that can be their own PR. If the review load is too big, happy to split them off.
Also treat `impl` definition parent as transparent regarding modules
This PR changes the `non_local_definitions` lint logic to also consider `impl` definition parent as transparent regarding modules.
See tests and explanation in the changes.
``````@rustbot`````` label +L-non_local_definitions
Fixes *(after beta-backport)* #132427
cc ``````@leighmcculloch``````
r? ``````@jieyouxu``````
Do not suggest `#[derive(Copy)]` when we wanted a `!Copy` type.
Do not say "`Copy` is not implemented for `T` but `Copy` is".
Do not talk about `Trait` having no implementations when `!Trait` was desired.
```
error[E0277]: the trait bound `{gen block@$DIR/gen_block_is_coro.rs:7:5: 7:8}: Coroutine` is not satisfied
--> $DIR/gen_block_is_coro.rs:6:13
|
LL | fn foo() -> impl Coroutine<Yield = u32, Return = ()> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Coroutine` is not implemented for `{gen block@$DIR/gen_block_is_coro.rs:7:5: 7:8}`
LL | gen { yield 42 }
| ---------------- return type was inferred to be `{gen block@$DIR/gen_block_is_coro.rs:7:5: 7:8}` here
```
The secondary span label is new.
When a trait is not implemented for a type, but there *is* an `impl`
for another type or different trait params, we format the output to
use highlighting in the same way that E0308 does for types.
The logic accounts for 3 cases:
- When both the type and trait in the expected predicate and the candidate are different
- When only the types are different
- When only the trait generic params are different
For each case, we use slightly different formatting and wording.
Rollup of 14 pull requests
Successful merges:
- #131829 (Remove support for `-Zprofile` (gcov-style coverage instrumentation))
- #132369 (style-guide: Only use the new binop heuristic for assignments)
- #132383 (Implement suggestion for never type fallback lints)
- #132413 (update offset_of! docs to reflect the stabilization of nesting)
- #132438 (Remove unncessary option for default rust-analyzer setting)
- #132439 (Add `f16` and `f128` to `invalid_nan_comparison`)
- #132444 (rustdoc: Directly use rustc_abi instead of reexports)
- #132445 (Cleanup attributes around unchecked shifts and unchecked negation in const)
- #132448 (Add missing backtick)
- #132450 (Show actual MIR when MIR building forgot to terminate block)
- #132451 (remove some unnecessary rustc_allow_const_fn_unstable)
- #132455 (make const_alloc_layout feature gate only about functions that are already stable)
- #132456 (Move remaining inline assembly test files into asm directory)
- #132459 (feat(byte_sub_ptr): unstably add ptr::byte_sub_ptr)
r? `@ghost`
`@rustbot` modify labels: rollup
On some architectures, vector types may have a different ABI depending
on whether the relevant target features are enabled. (The ABI when the
feature is disabled is often not specified, but LLVM implements some
de-facto ABI.)
As discussed in rust-lang/lang-team#235, this turns out to very easily
lead to unsound code.
This commit makes it a post-monomorphization future-incompat warning to
declare or call functions using those vector types in a context in which
the corresponding target features are disabled, if using an ABI for
which the difference is relevant. This ensures that these functions are
always called with a consistent ABI.
See the [nomination comment](https://github.com/rust-lang/rust/pull/127731#issuecomment-2288558187)
for more discussion.
Part of #116558
Add `f16` and `f128` to `invalid_nan_comparison`
Currently `f32_nan` and `f64_nan` are used to provide the `invalid_nan_comparison` lint. Since we have `f16_nan` and `f128_nan`, hook these up so the new float types get the same lints.
Implement suggestion for never type fallback lints
r? ```@WaffleLapkin```
Just opening this up for vibes; it's not done yet. I'd still like to make this suggestable in a few more cases before merge:
- [x] Try to annotate `_` -> `()`
- [x] Try to annotate local variables if they're un-annotated: `let x = ...` -> `let x: () = ...`
- [x] Try to annotate the self type of a `Trait::method()` -> `<() as Trait>::method()`.
The only other case we may want to suggest is a missing turbofish, like `f()` -> `f::<()>()`. That may be possible, but seems overly annoying.
This partly addresses https://github.com/rust-lang/rust/issues/132358; the other half of fixing that would be to make the error message a bit better, perhaps just special casing the `?` operator 🤔 I don't think I'll do that part.
Currently `f32_nan` and `f64_nan` are used to provide the
`invalid_nan_comparison` lint. Since we have `f16_nan` and `f128_nan`,
hook these up so the new float types get the same lints.
Improve missing_abi lint
This is for the migration lint for https://github.com/rust-lang/rfcs/pull/3722
It is not yet marked as an edition migration lint, because `Edition2027` doesn't exist yet.
The lint now includes a machine applicable suggestion:
```
warning: extern declarations without an explicit ABI are deprecated
--> src/main.rs:3:1
|
3 | extern fn a() {}
| ^^^^^^ help: explicitly specify the C ABI: `extern "C"`
|
```
Fix validation when lowering `?` trait bounds
Pass the unlowered (`rustc_hir`) polarity to `lower_poly_trait_ref`.
This allows us to actually *validate* that generic args are actually valid on `?Trait` paths. This actually regressed in #113671 because that PR changed the behavior where we were inadvertently re-lowering paths as `BoundPolarity::Positive`, which was also coincidentally the only place we were enforcing the generics on `?Trait` paths were correct.
Fix `target_os` for `mipsel-sony-psx`
Previously set to `target_os = "none"` and `target_env = "psx"` in [the PR introducing the target](https://github.com/rust-lang/rust/pull/102689/), but although the Playstation 1 is _close_ to a bare metal target in some regards, it's still very much an operating system, so we should instead set `target_os = "psx"`.
This also matches the `mipsel-sony-psp` target, which sets `target_os = "psp"`.
CC target maintainer ``@ayrtonm.``
If there's any code out there that uses `cfg(target_env = "psx")`, they can use `cfg(any(target_os = "psx", target_env = "psx"))` until they bump their MSRV to a version where this is fully fixed.
Mark `simplify_aggregate_to_copy` mir-opt as unsound
Mark the `simplify_aggregate_to_copy` mir-opt added in #128299 as unsound as it seems to miscompile the MCVE reported in https://github.com/rust-lang/rust/issues/132353. The mir-opt can be re-enabled once this case is fixed.
```rs
fn pop_min(mut score2head: Vec<Option<usize>>) -> Option<usize> {
loop {
if let Some(col) = score2head[0] {
score2head[0] = None;
return Some(col);
}
}
}
fn main() {
let min = pop_min(vec![Some(1)]);
println!("min: {:?}", min);
// panic happens here on beta in release mode
// but not in debug mode
min.unwrap();
}
```
This MCVE is included as a `run-pass` ui regression test in the first commit. I built the ui test with a nightly manually, and can reproduce the behavioral difference with `-C opt-level=0` and `-C opt-level=1`. Locally, this ui test will fail unless it was run on a compiler built with the second commit marking the mir-opt as unsound thus disabling it by default.
This PR **partially reverts** commit e7386b3, reversing changes made to 02b1be1. The mir-opt implementation is just marked as unsound but **not** reverted to make reland reviews easier. Test changes are **reverted if they were not pure additions**. Tests added by the original PR received `-Z unsound-mir-opts` compile-flags.
cc `@DianQK` `@cjgillot` (PR author and reviewer of #128299)
Add a new 'pc' option to -Z branch-protection for aarch64 that
enables the use of PC as a diversifier in PAC branch protection code.
When the pauth-lr target feature is enabled in combination
with -Z branch-protection=pac-ret,pc, the new 9.5-a instructions
(pacibsppc, retaasppc, etc) will be generated.
Rollup of 4 pull requests
Successful merges:
- #132347 (Remove `ValueAnalysis` and `ValueAnalysisWrapper`.)
- #132365 (pass `RUSTC_HOST_FLAGS` at once without the for loop)
- #132366 (Do not enforce `~const` constness effects in typeck if `rustc_do_not_const_check`)
- #132376 (Annotate `input` reference tests)
r? `@ghost`
`@rustbot` modify labels: rollup
Do not enforce `~const` constness effects in typeck if `rustc_do_not_const_check`
Fixes a slight inconsistency between HIR and MIR enforcement of `~const` :D
r? `@rust-lang/project-const-traits`
Try to point out when edition 2024 lifetime capture rules cause borrowck issues
Lifetime capture rules in 2024 are modified to capture more lifetimes, which sometimes lead to some non-local borrowck errors. This PR attempts to link these back together with a useful note pointing out the capture rule changes.
This is not a blocking concern, but I'd appreciate feedback (though, again, I'd like to stress that I don't want to block this PR on this): I'm worried about this note drowning in the sea of other diagnostics that borrowck emits. I was tempted to change the level of the note to `.span_warn` just so it would show up in a different color. Thoughts?
Fixes#130545
Opening as a draft first since it's stacked on #131183.
r? `@ghost`
Make sure `type_param_predicates` resolves correctly for RPITIT
After #132194, we end up lowering the item bounds for an RPITIT in an `ItemCtxt` whose def id is the *synthetic GAT*, not the opaque type from the HIR.
This means that when we're resolving a shorthand projection like `T::Assoc`, we call the `type_param_predicates` function with the `item_def_id` of the *GAT* and not the opaque. That function operates on the HIR, and is not designed to work with the `Node::Synthetic` that gets fed for items synthesized by the compiler...
This PR reuses the trick we use elsewhere in lowering, where we intercept whether an item comes from RPITIT lowering, and forwards the query off to the correct item.
Fixes#132372
Rename `rustc_abi::Abi` to `BackendRepr`
Remove the confabulation of `rustc_abi::Abi` with what "ABI" actually means by renaming it to `BackendRepr`, and rename `Abi::Aggregate` to `BackendRepr::Memory`. The type never actually represented how things are passed, as that has to have `PassMode` considered, at minimum, but rather it just is how we represented some things to the backend. This conflation arose because LLVM, the primary backend at the time, would lower certain IR forms using certain ABIs. Even that only somewhat was true, as it broke down when one ventured significantly afield of what is described by the System V AMD64 ABI either by using different architectures, ABI-modifying IR annotations, the same architecture **with different ISA extensions enabled**, or other... unexpected delights.
Unfortunately both names are still somewhat of a misnomer right now, as people have written code for years based on this misunderstanding. Still, their original names are even moreso, and for better or worse, this backend code hasn't received as much maintenance as the rest of the compiler, lately. Actually arriving at a correct end-state will simply require us to disentangle a lot of code in order to fix, much of it pointlessly repeated in several places. Thus this is not an "actual fix", just a way to deflect further misunderstandings.
Remap impl-trait lifetimes on HIR instead of AST lowering
Current AST->HIR lowering goes out of its way to remap lifetimes for opaque types. This is complicated and leaks into upstream and downstream code.
This PR stops trying to be clever during lowering, and prefers to do this remapping during the HIR->ty lowering. The remapping computation easily fits into the bound var resolution code. Its result can be used in by `generics_of` and `hir_ty_lowering::new_opaque` to add the proper parameters and arguments.
See an example on the doc for query `opaque_captured_lifetimes`.
Based on https://github.com/rust-lang/rust/pull/129244/
Fixes https://github.com/rust-lang/rust/issues/125249
Fixes https://github.com/rust-lang/rust/issues/126850
cc `@compiler-errors` `@spastorino`
r? `@petrochenkov`
The failure output is:
```
SplitVectorOperand Op #1: t51: i32 = llvm.wasm.alltrue TargetConstant:i32<12408>, t50
rustc-LLVM ERROR: Do not know how to split this operator's operand!
```
Reject generic self types.
The RFC for arbitrary self types v2 declares that we should reject "generic" self types. This commit does so.
The definition of "generic" was unclear in the RFC, but has been explored in
https://github.com/rust-lang/rust/issues/129147
and the conclusion is that "generic" means any `self` type which is a type parameter defined on the method itself, or references to such a type.
This approach was chosen because other definitions of "generic" don't work. Specifically,
* we can't filter out generic type _arguments_, because that would filter out Rc<Self> and all the other types of smart pointer we want to support;
* we can't filter out all type params, because Self itself is a type param, and because existing Rust code depends on other type params declared on the type (as opposed to the method).
This PR decides to make a new error code for this case, instead of reusing the existing E0307 error. This makes the code a bit more complex, but it seems we have an opportunity to provide specific diagnostics for this case so we should do so.
This PR filters out generic self types whether or not the 'arbitrary self types' feature is enabled. However, it's believed that it can't have any effect on code which uses stable Rust, since there are no stable traits which can be used to indicate a valid generic receiver type, and thus it would have been impossible to write code which could trigger this new error case. It is however possible that this could break existing code which uses either of the unstable `arbitrary_self_types` or `receiver_trait` features. This breakage is intentional; as we move arbitrary self types towards stabilization we don't want to continue to support generic such types.
This PR adds lots of extra tests to arbitrary-self-from-method-substs. Most of these are ways to trigger a "type mismatch" error which 9b82580c73/compiler/rustc_hir_typeck/src/method/confirm.rs (L519) hopes can be minimized by filtering out generics in this way. We remove a FIXME from confirm.rs suggesting that we make this change. It's still possible to cause type mismatch errors, and a subsequent PR may be able to improve diagnostics in this area, but it's harder to cause these errors without contrived uses of the turbofish.
This is a part of the arbitrary self types v2 project, https://github.com/rust-lang/rfcs/pull/3519https://github.com/rust-lang/rust/issues/44874
r? `@wesleywiser`
The RFC for arbitrary self types v2 declares that we should reject
"generic" self types. This commit does so.
The definition of "generic" was unclear in the RFC, but has been
explored in
https://github.com/rust-lang/rust/issues/129147
and the conclusion is that "generic" means any `self` type which
is a type parameter defined on the method itself, or references
to such a type.
This approach was chosen because other definitions of "generic"
don't work. Specifically,
* we can't filter out generic type _arguments_, because that would
filter out Rc<Self> and all the other types of smart pointer
we want to support;
* we can't filter out all type params, because Self itself is a
type param, and because existing Rust code depends on other
type params declared on the type (as opposed to the method).
This PR decides to make a new error code for this case, instead of
reusing the existing E0307 error. This makes the code a
bit more complex, but it seems we have an opportunity to provide
specific diagnostics for this case so we should do so.
This PR filters out generic self types whether or not the
'arbitrary self types' feature is enabled. However, it's believed
that it can't have any effect on code which uses stable Rust, since
there are no stable traits which can be used to indicate a valid
generic receiver type, and thus it would have been impossible to
write code which could trigger this new error case.
It is however possible that this could break existing code which
uses either of the unstable `arbitrary_self_types` or
`receiver_trait` features. This breakage is intentional; as
we move arbitrary self types towards stabilization we don't want
to continue to support generic such types.
This PR adds lots of extra tests to arbitrary-self-from-method-substs.
Most of these are ways to trigger a "type mismatch" error which
9b82580c73/compiler/rustc_hir_typeck/src/method/confirm.rs (L519)
hopes can be minimized by filtering out generics in this way.
We remove a FIXME from confirm.rs suggesting that we make this change.
It's still possible to cause type mismatch errors, and a subsequent
PR may be able to improve diagnostics in this area, but it's harder
to cause these errors without contrived uses of the turbofish.
This is a part of the arbitrary self types v2 project,
https://github.com/rust-lang/rfcs/pull/3519https://github.com/rust-lang/rust/issues/44874
r? @wesleywiser
Fix directives for lint-non-snake-case-crate
This test fails on targets without unwinding or with `--target-rustcflags=-Cpanic=abort` because the proc macro was compiled as the target, not the host. Some targets were explicitly disabled to pass CI, but these directives are more general.
* `needs-dynamic-linking` is self explanatory
* `force-host` for proc macros
* `no-prefer-dynamic` is apparently also used for proc macros
Note that `needs-unwind` can also be useful for situations other than proc macros where unwinding is necessary.
r? `@jieyouxu`
try-job: test-various
Use `token_descr` more in error messages
This is the first two commits from #124141, put into their own PR to get things rolling. Commit messages have the details.
r? ``@estebank``
cc ``@petrochenkov``
Don't lint `irrefutable_let_patterns` on leading patterns if `else if` let-chains
fixes#128661
Is there any preference where the test goes? There looks to be several places it could fit.
This test fails on targets without unwinding because the proc macro was
compiled as the target, not the host. Some targets were explicitly
disabled to pass CI, but these directives are more general.
Fixes Fuchsia tests.
Remove detail from label/note that is already available in other note
Remove the "which is required by `{root_obligation}`" post-script in
"the trait `X` is not implemented for `Y`" explanation in E0277. This
information is already conveyed in the notes explaining requirements,
making it redundant while making the text (particularly in labels)
harder to read.
```
error[E0277]: the trait bound `NotCopy: Copy` is not satisfied
--> $DIR/wf-static-type.rs:10:13
|
LL | static FOO: IsCopy<Option<NotCopy>> = IsCopy { t: None };
| ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`
|
= note: required for `Option<NotCopy>` to implement `Copy`
note: required by a bound in `IsCopy`
--> $DIR/wf-static-type.rs:7:17
|
LL | struct IsCopy<T:Copy> { t: T }
| ^^^^ required by this bound in `IsCopy`
```
vs the prior
```
error[E0277]: the trait bound `NotCopy: Copy` is not satisfied
--> $DIR/wf-static-type.rs:10:13
|
LL | static FOO: IsCopy<Option<NotCopy>> = IsCopy { t: None };
| ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`, which is required by `Option<NotCopy>: Copy`
|
= note: required for `Option<NotCopy>` to implement `Copy`
note: required by a bound in `IsCopy`
--> $DIR/wf-static-type.rs:7:17
|
LL | struct IsCopy<T:Copy> { t: T }
| ^^^^ required by this bound in `IsCopy`
```
*Ignore first three commits from https://github.com/rust-lang/rust/pull/132086.*
Ensure that resume arg outlives region bound for coroutines
When proving that `{Coroutine}: 'region`, we must also prove that the coroutine's resume ty outlives that region as well. See the inline comment.
Fixes#132104
Remove the "which is required by `{root_obligation}`" post-script in
"the trait `X` is not implemented for `Y`" explanation in E0277. This
information is already conveyed in the notes explaining requirements,
making it redundant while making the text (particularly in labels)
harder to read.
```
error[E0277]: the trait bound `NotCopy: Copy` is not satisfied
--> $DIR/wf-static-type.rs:10:13
|
LL | static FOO: IsCopy<Option<NotCopy>> = IsCopy { t: None };
| ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`
|
= note: required for `Option<NotCopy>` to implement `Copy`
note: required by a bound in `IsCopy`
--> $DIR/wf-static-type.rs:7:17
|
LL | struct IsCopy<T:Copy> { t: T }
| ^^^^ required by this bound in `IsCopy`
```
vs the prior
```
error[E0277]: the trait bound `NotCopy: Copy` is not satisfied
--> $DIR/wf-static-type.rs:10:13
|
LL | static FOO: IsCopy<Option<NotCopy>> = IsCopy { t: None };
| ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`, which is required by `Option<NotCopy>: Copy`
|
= note: required for `Option<NotCopy>` to implement `Copy`
note: required by a bound in `IsCopy`
--> $DIR/wf-static-type.rs:7:17
|
LL | struct IsCopy<T:Copy> { t: T }
| ^^^^ required by this bound in `IsCopy`
```
Collect item bounds for RPITITs from trait where clauses just like associated types
We collect item bounds from trait where clauses for *associated types*, i.e. this:
```rust
trait Foo
where
Self::Assoc: Send
{
type Assoc;
}
```
Becomes this:
```rust
trait Foo {
type Assoc: Send;
}
```
Today, with RPITITs/AFIT and return-type notation, we don't do that, i.e.:
```rust
trait Foo where Self::method(..): Send {
fn method() -> impl Sized;
}
fn is_send(_: impl Send) {}
fn test<T: Foo>() {
is_send(T::method());
}
```
...which fails on nightly today.
Turns out it's super easy to fix this, and we just need to use the `associated_type_bounds` lowering function in `explicit_item_bounds_with_filter`, which has that logic baked in.
Hack out effects support for old solver
Opening this for vibes ✨
Turns out that a basic, somewhat incomplete implementation of host effects is achievable in the old trait solver pretty easily. This should be sufficient for us to use in the standard library itself.
Regarding incompleteness, maybe we should always treat host predicates as ambiguous in intercrate mode (at least in the old solver) to avoid any worries about accidental impl overlap or something.
r? ```@lcnr``` cc ```@fee1-dead```
Lint against getting pointers from immediately dropped temporaries
Fixes#123613
## Changes:
1. New lint: `dangling_pointers_from_temporaries`. Is a generalization of `temporary_cstring_as_ptr` for more types and more ways to get a temporary.
2. `temporary_cstring_as_ptr` is removed and marked as renamed to `dangling_pointers_from_temporaries`.
3. `clippy::temporary_cstring_as_ptr` is marked as renamed to `dangling_pointers_from_temporaries`.
4. Fixed a false positive[^fp] for when the pointer is not actually dangling because of lifetime extension for function/method call arguments.
5. `core::cell::Cell` is now `rustc_diagnostic_item = "Cell"`
## Questions:
- [ ] Instead of manually checking for a list of known methods and diagnostic items, maybe add some sort of annotation to those methods in library and check for the presence of that annotation? https://github.com/rust-lang/rust/pull/128985#issuecomment-2318714312
## Known limitations:
### False negatives[^fn]:
See the comments in `compiler/rustc_lint/src/dangling.rs`
1. Method calls that are not checked for:
- `temporary_unsafe_cell.get()`
- `temporary_sync_unsafe_cell.get()`
2. Ways to get a temporary that are not recognized:
- `owning_temporary.field`
- `owning_temporary[index]`
3. No checks for ref-to-ptr conversions:
- `&raw [mut] temporary`
- `&temporary as *(const|mut) _`
- `ptr::from_ref(&temporary)` and friends
[^fn]: lint **should** be emitted, but **is not**
[^fp]: lint **should not** be emitted, but **is**
Lower AST node id only once
Fixes#96346.
I basically followed the given instructions except the inline part.
`lower_jump_destination` can't reuse local existing `HirId` due to unknown name resolution result so I created an additional mapping for labels.
r? ```@cjgillot```
This commit adds a new rustc target feature named `wide-arithmetic` for
WebAssembly targets. This corresponds to the [wide-arithmetic] proposal
for WebAssembly which adds new instructions catered towards accelerating
integer arithmetic larger than 64-bits. This proposal to WebAssembly is
not standard yet so this new feature is flagged as an unstable target
feature. Additionally Rust's LLVM version doesn't support this new
feature yet since support will first be added in LLVM 20, so the
feature filtering logic for LLVM is updated to handle this.
I'll also note that I'm not currently planning to add wasm-specific
intrinsics to `std::arch::wasm32` at this time. The currently proposed
instructions are all accessible through `i128` or `u128`-based
operations which Rust already supports, so intrinsic shouldn't be
necessary to get access to these new instructions.
[wide-arithmetic]: https://github.com/WebAssembly/wide-arithmetic
Rollup of 4 pull requests
Successful merges:
- #131391 (Stabilize `isqrt` feature)
- #132248 (rustc_transmute: Directly use types from rustc_abi)
- #132252 (compiler: rename LayoutS to LayoutData)
- #132253 (Known-bug test for `keyword_idents` lint not propagating to other files)
r? `@ghost`
`@rustbot` modify labels: rollup
Known-bug test for `keyword_idents` lint not propagating to other files
Known-bug test for `keyword_idents` lint not propagating to other files when configured via attribute (#132218).
fix various linker warnings
separated out from https://github.com/rust-lang/rust/pull/119286; this doesn't have anything user-facing, i just want to land these changes so i can stop rebasing them.
r? `@bjorn3`
Remove `ObligationCause::span()` method
I think it's an incredibly confusing footgun to expose both `obligation_cause.span` and `obligation_cause.span()`. Especially because `ObligationCause::span()` (the method) seems to just be hacking around a single quirk in the way we set up obligation causes for match arms.
First commit removes the need for that hack, with only one diagnostic span changing (but IMO not really getting worse -- I'd argue that it was already confusing).
Much like the previous commit.
I think the removal of "the token" in each message is fine here. There
are many more error messages that mention tokens without saying "the
token" than those that do say it.
By using `token_descr`, as is done for many other errors, we can get
slightly better descriptions in error messages, e.g.
"macro expansion ignores token `let` and any following" becomes
"macro expansion ignores keyword `let` and any tokens following".
This will be more important once invisible delimiters start being
mentioned in error messages -- without this commit, that leads to error
messages such as "error at ``" because invisible delimiters are
pretty printed as an empty string.
this makes it much easier to understand test failures.
before:
```
diff of stderr:
1 error: linking with `LINKER` failed: exit status: 1
2 |
- ld: Undefined symbols:
4 _CFRunLoopGetTypeID, referenced from:
5 clang: error: linker command failed with exit code 1 (use -v to see invocation)
```
after:
```
=== HAYSTACK ===
error: linking with `cc` failed: exit status: 1
|
= note: use `--verbose` to show all linker arguments
= note: Undefined symbols for architecture arm64:
"_CFRunLoopGetTypeID", referenced from:
main::main::hbb553f5dda62d3ea in main.main.d17f5fbe6225cf88-cgu.0.rcgu.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: aborting due to 1 previous error
=== NEEDLE ===
_CFRunLoopGetTypeID\.?, referenced from:
thread 'main' panicked at /Users/jyn/git/rust-lang/rust/tests/run-make/linkage-attr-framework/rmake.rs:22:10:
needle was not found in haystack
```
this also fixes a failure related to missing whitespace; we don't actually care about whitespace in this test.
Cleanup: Move an impl-Trait check from AST validation to AST lowering
Namely the one that rejects `impl Trait` in qself types and non-final path segments.
There's no good reason to perform this during AST validation.
We have better infrastructure in place in the AST lowerer (`ImplTraitContext`).
This shaves off a lot of code.
We now lower `impl Trait` in bad positions to `{type error}` which allows us to
remove a special case from HIR ty lowering.
Coincidentally fixes#126725. Well, it only *masks* it by passing `{type error}` to HIR analysis instead of a "bad" opaque. I was able to find a new reproducer for it. See the issue.
Rename macro `SmartPointer` to `CoercePointee`
As per resolution #129104 we will rename the macro to better reflect the technical specification of the feature and clarify the communication.
- `SmartPointer` is renamed to `CoerceReferent`
- `#[pointee]` attribute is renamed to `#[referent]`
- `#![feature(derive_smart_pointer)]` gate is renamed to `#![feature(derive_coerce_referent)]`.
- Any mention of `SmartPointer` in the file names are renamed accordingly.
r? `@compiler-errors`
cc `@nikomatsakis` `@Darksonn`
rustc_target: Add pauth-lr aarch64 target feature
Add the pauth-lr target feature, corresponding to aarch64 FEAT_PAuth_LR. This feature has been added in LLVM 19.
It is currently not supported by the Linux hwcap and so we cannot add runtime feature detection for it at this time.
r? `@Amanieu`
Deny calls to non-`#[const_trait]` methods in MIR constck
This is a (potentially temporary) fix that closes off the mismatch in assumptions between MIR constck and typeck which does the const traits checking. Before this PR, MIR constck assumed that typeck correctly handled all calls to trait methods in const contexts if effects is enabled. That is not true because typeck only correctly handles callees that are const. For non-const callees (such as methods in a non-const_trait), typeck had never created an error.
45089ec19e/compiler/rustc_hir_typeck/src/callee.rs (L876-L877)
I called this potentially temporary because the const checks could be moved to HIR entirely. Alongside the recent refactor in const stability checks where that component could be placed would need more discussion. (cc ```@compiler-errors``` ```@RalfJung)```
Tests are updated, mainly due to traits not being const in core, so tests that call them correctly error.
This fixes https://github.com/rust-lang/project-const-traits/issues/12.
Const stability checks v2
The const stability system has served us well ever since `const fn` were first stabilized. It's main feature is that it enforces *recursive* validity -- a stable const fn cannot internally make use of unstable const features without an explicit marker in the form of `#[rustc_allow_const_fn_unstable]`. This is done to make sure that we don't accidentally expose unstable const features on stable in a way that would be hard to take back. As part of this, it is enforced that a `#[rustc_const_stable]` can only call `#[rustc_const_stable]` functions. However, some problems have been coming up with increased usage:
- It is baffling that we have to mark private or even unstable functions as `#[rustc_const_stable]` when they are used as helpers in regular stable `const fn`, and often people will rather add `#[rustc_allow_const_fn_unstable]` instead which was not our intention.
- The system has several gaping holes: a private `const fn` without stability attributes whose inherited stability (walking up parent modules) is `#[stable]` is allowed to call *arbitrary* unstable const operations, but can itself be called from stable `const fn`. Similarly, `#[allow_internal_unstable]` on a macro completely bypasses the recursive nature of the check.
Fundamentally, the problem is that we have *three* disjoint categories of functions, and not enough attributes to distinguish them:
1. const-stable functions
2. private/unstable functions that are meant to be callable from const-stable functions
3. functions that can make use of unstable const features
Functions in the first two categories cannot use unstable const features and they can only call functions from the first two categories.
This PR implements the following system:
- `#[rustc_const_stable]` puts functions in the first category. It may only be applied to `#[stable]` functions.
- `#[rustc_const_unstable]` by default puts functions in the third category. The new attribute `#[rustc_const_stable_indirect]` can be added to such a function to move it into the second category.
- `const fn` without a const stability marker are in the second category if they are still unstable. They automatically inherit the feature gate for regular calls, it can now also be used for const-calls.
Also, all the holes mentioned above have been closed. There's still one potential hole that is hard to avoid, which is when MIR building automatically inserts calls to a particular function in stable functions -- which happens in the panic machinery. Those need to be manually marked `#[rustc_const_stable_indirect]` to be sure they follow recursive const stability. But that's a fairly rare and special case so IMO it's fine.
The net effect of this is that a `#[unstable]` or unmarked function can be constified simply by marking it as `const fn`, and it will then be const-callable from stable `const fn` and subject to recursive const stability requirements. If it is publicly reachable (which implies it cannot be unmarked), it will be const-unstable under the same feature gate. Only if the function ever becomes `#[stable]` does it need a `#[rustc_const_unstable]` or `#[rustc_const_stable]` marker to decide if this should also imply const-stability.
Adding `#[rustc_const_unstable]` is only needed for (a) functions that need to use unstable const lang features (including intrinsics), or (b) `#[stable]` functions that are not yet intended to be const-stable. Adding `#[rustc_const_stable]` is only needed for functions that are actually meant to be directly callable from stable const code. `#[rustc_const_stable_indirect]` is used to mark intrinsics as const-callable and for `#[rustc_const_unstable]` functions that are actually called from other, exposed-on-stable `const fn`. No other attributes are required.
Also see the updated dev-guide at https://github.com/rust-lang/rustc-dev-guide/pull/2098.
I think in the future we may want to tweak this further, so that in the hopefully common case where a public function's const-stability just exactly mirrors its regular stability, we never have to add any attribute. But right now, once the function is stable this requires `#[rustc_const_stable]`.
### Open question
There is one point I could see we might want to do differently, and that is putting `#[rustc_const_unstable]` functions (but not intrinsics) in category 2 by default, and requiring an extra attribute for `#[rustc_const_not_exposed_on_stable]` or so. This would require a bunch of extra annotations, but would have the advantage that turning a `#[rustc_const_unstable]` into `#[rustc_const_stable]` will never change the way the function is const-checked. Currently, we often discover in the const stabilization PR that a function needs some other unstable const things, and then we rush to quickly deal with that. In this alternative universe, we'd work towards getting rid of the `rustc_const_not_exposed_on_stable` before stabilization, and once that is done stabilization becomes a trivial matter. `#[rustc_const_stable_indirect]` would then only be used for intrinsics.
I think I like this idea, but might want to do it in a follow-up PR, as it will need a whole bunch of annotations in the standard library. Also, we probably want to convert all const intrinsics to the "new" form (`#[rustc_intrinsic]` instead of an `extern` block) before doing this to avoid having to deal with two different ways of declaring intrinsics.
Cc `@rust-lang/wg-const-eval` `@rust-lang/libs-api`
Part of https://github.com/rust-lang/rust/issues/129815 (but not finished since this is not yet sufficient to safely let us expose `const fn` from hashbrown)
Fixes https://github.com/rust-lang/rust/issues/131073 by making it so that const-stable functions are always stable
try-job: test-various
Fundamentally, we have *three* disjoint categories of functions:
1. const-stable functions
2. private/unstable functions that are meant to be callable from const-stable functions
3. functions that can make use of unstable const features
This PR implements the following system:
- `#[rustc_const_stable]` puts functions in the first category. It may only be applied to `#[stable]` functions.
- `#[rustc_const_unstable]` by default puts functions in the third category. The new attribute `#[rustc_const_stable_indirect]` can be added to such a function to move it into the second category.
- `const fn` without a const stability marker are in the second category if they are still unstable. They automatically inherit the feature gate for regular calls, it can now also be used for const-calls.
Also, several holes in recursive const stability checking are being closed.
There's still one potential hole that is hard to avoid, which is when MIR
building automatically inserts calls to a particular function in stable
functions -- which happens in the panic machinery. Those need to *not* be
`rustc_const_unstable` (or manually get a `rustc_const_stable_indirect`) to be
sure they follow recursive const stability. But that's a fairly rare and special
case so IMO it's fine.
The net effect of this is that a `#[unstable]` or unmarked function can be
constified simply by marking it as `const fn`, and it will then be
const-callable from stable `const fn` and subject to recursive const stability
requirements. If it is publicly reachable (which implies it cannot be unmarked),
it will be const-unstable under the same feature gate. Only if the function ever
becomes `#[stable]` does it need a `#[rustc_const_unstable]` or
`#[rustc_const_stable]` marker to decide if this should also imply
const-stability.
Adding `#[rustc_const_unstable]` is only needed for (a) functions that need to
use unstable const lang features (including intrinsics), or (b) `#[stable]`
functions that are not yet intended to be const-stable. Adding
`#[rustc_const_stable]` is only needed for functions that are actually meant to
be directly callable from stable const code. `#[rustc_const_stable_indirect]` is
used to mark intrinsics as const-callable and for `#[rustc_const_unstable]`
functions that are actually called from other, exposed-on-stable `const fn`. No
other attributes are required.
When printing
```
= help: the trait `chumsky::private::ParserSealed<'_, &'a str, ((), ()), chumsky::extra::Full<EmptyErr, (), ()>>` is implemented for `Then<Ignored<chumsky::combinator::Filter<chumsky::primitive::Any<&str, chumsky::extra::Full<EmptyErr, (), ()>>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map<impl CSTParser<'a, O>, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full<EmptyErr, (), ()>>`
= help: for that trait implementation, expected `((), ())`, found `()`
```
Highlight only the `expected` and `found` types, instead of the full type in the first `help`.
Emit future-incompatibility lint when calling/declaring functions with vectors that require missing target feature
On some architectures, vector types may have a different ABI depending on whether the relevant target features are enabled. (The ABI when the feature is disabled is often not specified, but LLVM implements some de-facto ABI.)
As discussed in https://github.com/rust-lang/lang-team/issues/235, this turns out to very easily lead to unsound code.
This commit makes it a post-monomorphization error to declare or call functions using those vector types in a context in which the corresponding target features are disabled, if using an ABI for which the difference is relevant. This ensures that these functions are always called with a consistent ABI.
See the [nomination comment](https://github.com/rust-lang/rust/pull/127731#issuecomment-2288558187) for more discussion.
r? RalfJung
Part of https://github.com/rust-lang/rust/issues/116558
On some architectures, vector types may have a different ABI when
relevant target features are enabled.
As discussed in https://github.com/rust-lang/lang-team/issues/235, this
turns out to very easily lead to unsound code.
This commit makes it an error to declare or call functions using those
vector types in a context in which the corresponding target features are
disabled, if using an ABI for which the difference is relevant.
Add support for `~const` item bounds
Supports the only missing capability of `~const` associated types that I can think of now (this is obviously excluding `~const` opaques, which I see as an extension to this; I'll probably do that next).
r? ``@lcnr`` mostly b/c it changes candidate assembly, or reassign
cc ``@fee1-dead``
Stabilize shorter-tail-lifetimes
Close#131445
Tracked by #123739
We found a test case `tests/ui/drop/drop_order.rs` that had not been covered by the change. The test fixture is fixed now with the correct expectation.
Represent trait constness as a distinct predicate
cc `@rust-lang/project-const-traits`
r? `@ghost` for now
Also mirrored everything that is written below on this hackmd here: https://hackmd.io/`@compiler-errors/r12zoixg1l`
# Tl;dr:
* This PR removes the bulk of the old effect desugaring.
* This PR reimplements most of the effect desugaring as a new predicate and set of a couple queries. I believe it majorly simplifies the implementation and allows us to move forward more easily on its implementation.
I'm putting this up both as a request for comments and a vibe-check, but also as a legitimate implementation that I'd like to see land (though no rush of course on that last part).
## Background
### Early days
Once upon a time, we represented trait constness in the param-env and in `TraitPredicate`. This was very difficult to implement correctly; it had bugs and was also incomplete; I don't think this was anyone's fault though, it was just the limit of experimental knowledge we had at that point.
Dealing with `~const` within predicates themselves meant dealing with constness all throughout the trait solver. This was difficult to keep track of, and afaict was not handled well with all the corners of candidate assembly.
Specifically, we had to (in various places) remap constness according to the param-env constness:
574b64a97f/compiler/rustc_trait_selection/src/traits/select/mod.rs (L1498)
This was annoying and manual and also error prone.
### Beginning of the effects desugaring
Later on, #113210 reimplemented a new desugaring for const traits via a `<const HOST: bool>` predicate. This essentially "reified" the const checking and separated it from any of the remapping or separate tracking in param-envs. For example, if I was in a const-if-const environment, but I wanted to call a trait that was non-const, this reification would turn the constness mismatch into a simple *type* mismatch of the effect parameter.
While this was a monumental step towards straightening out const trait checking in the trait system, it had its own issues, since that meant that the constness of a trait (or any item within it, like an associated type) was *early-bound*. This essentially meant that `<T as Trait>::Assoc` was *distinct* from `<T as ~const Trait>::Assoc`, which was bad.
### Associated-type bound based effects desugaring
After this, #120639 implemented a new effects desugaring. This used an associated type to more clearly represent the fact that the constness is not an input parameter of a trait, but a property that could be computed of a impl. The write-up linked in that PR explains it better than I could.
However, I feel like it really reached the limits of what can comfortably be expressed in terms of associated type and trait calculus. Also, `<const HOST: bool>` remains a synthetic const parameter, which is observable in nested items like RPITs and closures, and comes with tons of its own hacks in the astconv and middle layer.
For example, there are pieces of unintuitive code that are needed to represent semantics like elaboration, and eventually will be needed to make error reporting intuitive, and hopefully in the future assist us in implementing built-in traits (eventually we'll want something like `~const Fn` trait bounds!).
elaboration hack: 8069f8d17a/compiler/rustc_type_ir/src/elaborate.rs (L133-L195)
trait bound remapping hack for diagnostics: 8069f8d17a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs (L2370-L2413)
I want to be clear that I don't think this is a issue of implementation quality or anything like that; I think it's simply a very clear sign that we're using types and traits in a way that they're not fundamentally supposed to be used, especially given that constness deserves to be represented as a first-class concept.
### What now?
This PR implements a new desugaring for const traits. Specifically, it introduces a `HostEffect` predicate to represent the obligation an impl is const, rather than using associated type bounds and the compat trait that exists for effects today.
### `HostEffect` predicate
A `HostEffect` clause has two parts -- the `TraitRef` we're trying to prove, and a `HostPolarity::{Maybe, Const}`.
`HostPolarity::Const` corresponds to `T: const Trait` bounds, which must *always* be proven as const, and which can be written in any context. These are lowered directly into the predicates of an item, since they're not "context-specific".
On the other hand, `HostPolarity::Maybe` corresponds to `T: ~const Trait` bounds which must only exist in a conditionally-const context like a method in a `#[const_trait]`, or a `const fn` free function. We do not lower these immediately into the predicates of an item; instead, we collect them into a new query called the **`const_conditions`**. These are the set of trait refs that we need to prove have const implementations for an item to be const.
Notably, they're represented as bare (poly) trait refs because they are meant to be paired back together with a `HostPolarity` when they're being registered in typeck (see next section).
For example, given:
```rust
const fn foo<T: ~const A + const B>() {}
```
`foo`'s const conditions would contain `T: A`, but not `T: B`. On the flip side, foo's predicates (`predicates_of`) query would contain `HostEffect(T: B, HostPolarity::Const)` but not `HostEffect(T: A, HostPolarity::Maybe)` since we don't need to prove that predicate in a non-const environment (and it's not even the right predicate to prove in an unconditionally const environment).
### Type checking const bodies
When type checking bodies in HIR, when we encounter a call expression, we additionally register the callee item's const conditions with the `HostPolarity` from the body we're typechecking (`Const` for unconditionally const things like `const`/`static` items, and `Maybe` for conditionally const things like const fns; and we don't register `HostPolarity` predicates for non-const bodies).
When type-checking a conditionally const body, we augment its param-env with `HostEffect(..., Maybe)` predicates.
### Checking that const impls are WF
We extend the logic in `compare_method_predicate_entailment` to also check the const-conditions of the impl method, to make sure that we error for:
```rust
#[const_trait] Bar {}
#[const_trait] trait Foo {
fn method<T: Bar>();
}
impl Foo for () {
fn method<T: ~const Bar>() {} // stronger assumption!
}
```
We also extend the WF check for impls to register the const conditions of the trait that is being implemented. This is to make sure we error for:
```rust
#[const_trait] trait Bar {}
#[const_trait] trait Foo<T> where T: ~const Bar {}
impl<T> const Foo<T> for () {}
//~^ `T: ~const Bar` is missing!
```
### Proving a `HostEffect` predicate
We have several ways of proving a `HostEffect` predicate:
1. Matching a `HostEffect` predicate from the param-env
2. From an impl - we do impl selection very similar to confirming a trait goal, except we filter for only const impls, and we additionally register the impl's const conditions (i.e. the impl's `~const` where clauses).
Later I expect that we will add more built-in implementations for things like `Fn`.
## What next?
After this PR, I'd like to split out the work more so it can proceed in parallel and probably amongst others that are not me.
* Register `HostEffect` goal for places in HIR typeck that correspond to call terminators, like autoderef.
* Make traits in libstd const again.
* Probably need to impl host effect preds in old solver.
* Implement built-in `HostEffect` rules for traits like `Fn`.
* Rip out const checking from MIR altogether.
## So what?
This ends up being super convenient basically everywhere in the compiler. Due to the design of the new trait solver, we end up having an almost parallel structure to the existing trait and projection predicates for assembling `HostEffect` predicates; adding new candidates and especially new built-in implementations is now basically trivial, and it's quite straightforward to understand the confirmation logic for these predicates.
Same with diagnostics reporting; since we have predicates which represent the obligation to prove an impl is const, we can simplify and make these diagnostics richer without having to write a ton of logic to intercept and rewrite the existing `Compat` trait errors.
Finally, it gives us a much more straightforward path for supporting the const effect on the old trait solver. I'm personally quite passionate about getting const trait support into the hands of users without having to wait until the new solver lands[^1], so I think after this PR lands we can begin to gauge how difficult it would be to implement constness in the old trait solver too. This PR will not do this yet.
[^1]: Though this is not a prerequisite or by any means the only justification for this PR.
Consider param-env candidates even if they have errors
I added this logic in https://github.com/rust-lang/rust/pull/106309, but frankly I don't know why -- the logic was a very large hammer. It seems like recent changes to error tainting has made that no longer necessary.
Ideally we'd rework the way we handle error reporting in all of candidate assembly to be a bit more responsible; we're just suppressing candidates all willy-nilly and it leads to mysterious *other* errors cropping up, like the one that #132082 originally wanted to fix.
**N.B.** This has the side-effect of turning a failed resolution like `where Missing: Sized` into a trivial where clause that matches all types, but also I don't think it really matters?
I'm putting this up as an alternative to #132082, since that PR doesn't address the case when one desugars the APIT into a regular type param.
r? lcnr vibeck
Taking a raw ref (`&raw (const|mut)`) of a deref of pointer (`*ptr`) is always safe
T-opsem decided in https://github.com/rust-lang/reference/pull/1387 that `*ptr` is only unsafe if the place is accessed. This means that taking a raw ref of a deref expr is always safe, since it doesn't constitute a read.
This also relaxes the `DEREF_NULLPTR` lint to stop warning in the case of raw ref of a deref'd nullptr, and updates its docs to reflect that change in the UB specification.
This does not change the behavior of `addr_of!((*ptr).field)`, since field projections still require the projection is in-bounds.
I'm on the fence whether this requires an FCP, since it's something that is guaranteed by the reference you could ostensibly call this a bugfix since we were counting truly safe operations as unsafe. Perhaps someone on opsem has a strong opinion? cc `@rust-lang/opsem`
Don't allow test revisions that conflict with built in cfgs
Fixes#128964
Sorry `@heysujal` I started working on this about 1 minute before your comment by complete coincidence 😅
minor `*dyn` cast cleanup
Small follow-up to https://github.com/rust-lang/rust/pull/130234 to remove a redundant check and clean up comments. No functional changes.
Also, explain why casts cannot drop the principal even though coercions can, and add a test because apparently we didn't have one already.
r? `@WaffleLapkin` or `@compiler-errors`
Deeply normalize `TypeTrace` when reporting type error in new solver
Normalize the values that come from the `TypeTrace` for various type mismatches.
Side-note: We can't normalize the `TypeError` itself bc it may come from instantiated binders, so it may reference values from within the probe...
r? lcnr
Rename Receiver -> LegacyReceiver
As part of the "arbitrary self types v2" project, we are going to replace the current `Receiver` trait with a new mechanism based on a new, different `Receiver` trait.
This PR renames the old trait to get it out the way. Naming is hard. Options considered included:
* HardCodedReceiver (because it should only be used for things in the standard library, and hence is sort-of hard coded)
* LegacyReceiver
* TargetLessReceiver
* OldReceiver
These are all bad names, but fortunately this will be temporary. Assuming the new mechanism proceeds to stabilization as intended, the legacy trait will be removed altogether.
Although we expect this trait to be used only in the standard library, we suspect it may be in use elsehwere, so we're landing this change separately to identify any surprising breakages.
It's known that this trait is used within the Rust for Linux project; a patch is in progress to remove their dependency.
This is a part of the arbitrary self types v2 project,
https://github.com/rust-lang/rfcs/pull/3519https://github.com/rust-lang/rust/issues/44874
r? `@wesleywiser`
Rollup of 8 pull requests
Successful merges:
- #125205 (Fixup Windows verbatim paths when used with the `include!` macro)
- #131049 (Validate args are correct for `UnevaluatedConst`, `ExistentialTraitRef`/`ExistentialProjection`)
- #131549 (Add a note for `?` on a `impl Future<Output = Result<..>>` in sync function)
- #131731 (add `TestFloatParse` to `tools.rs` for bootstrap)
- #131732 (Add doc(plugins), doc(passes), etc. to INVALID_DOC_ATTRIBUTES)
- #132006 (don't stage-off to previous compiler when CI rustc is available)
- #132022 (Move `cmp_in_dominator_order` out of graph dominator computation)
- #132033 (compiletest: Make `line_directive` return a `DirectiveLine`)
r? `@ghost`
`@rustbot` modify labels: rollup
Add a note for `?` on a `impl Future<Output = Result<..>>` in sync function
It's confusing to `?` a future of a result in a sync function. We have a suggestion to `.await` it if we're in an async function, but not a sync function. Note that this is the case for sync functions, at least.
Let's be a bit more vague about a fix, since it's somewhat context dependent. For example, you could block on it, or you could make your function asynchronous. 🤷
As part of the "arbitrary self types v2" project, we are going to
replace the current `Receiver` trait with a new mechanism based on a
new, different `Receiver` trait.
This PR renames the old trait to get it out the way. Naming is hard.
Options considered included:
* HardCodedReceiver (because it should only be used for things in the
standard library, and hence is sort-of hard coded)
* LegacyReceiver
* TargetLessReceiver
* OldReceiver
These are all bad names, but fortunately this will be temporary.
Assuming the new mechanism proceeds to stabilization as intended, the
legacy trait will be removed altogether.
Although we expect this trait to be used only in the standard library,
we suspect it may be in use elsehwere, so we're landing this change
separately to identify any surprising breakages.
It's known that this trait is used within the Rust for Linux project; a
patch is in progress to remove their dependency.
This is a part of the arbitrary self types v2 project,
https://github.com/rust-lang/rfcs/pull/3519https://github.com/rust-lang/rust/issues/44874
r? @wesleywiser
terminology: #[feature] *enables* a feature (instead of "declaring" or "activating" it)
Mostly, we currently call a feature that has a corresponding `#[feature(name)]` attribute in the current crate a "declared" feature. I think that is confusing as it does not align with what "declaring" usually means. Furthermore, we *also* refer to `#[stable]`/`#[unstable]` as *declaring* a feature (e.g. in [these diagnostics](f25e5abea2/compiler/rustc_passes/messages.ftl (L297-L301))), which aligns better with what "declaring" usually means. To make things worse, the functions `tcx.features().active(...)` and `tcx.features().declared(...)` both exist and they are doing almost the same thing (testing whether a corresponding `#[feature(name)]` exists) except that `active` would ICE if the feature is not an unstable lang feature. On top of this, the callback when a feature is activated/declared is called `set_enabled`, and many comments also talk about "enabling" a feature.
So really, our terminology is just a mess.
I would suggest we use "declaring a feature" for saying that something is/was guarded by a feature (e.g. `#[stable]`/`#[unstable]`), and "enabling a feature" for `#[feature(name)]`. This PR implements that.
Move const trait tests from `ui/rfcs/rfc-2632-const-trait-impl` to `ui/traits/const-traits`
I found the old test directory to be somewhat long to name, and I don't think it's necessary to put an experimental implementation's tests under an rfc which is closed.
r? fee1-dead
Breaking this out of #131985 so that PR doesn't touch 300 files.
rust_for_linux: -Zregparm=<N> commandline flag for X86 (#116972)
Command line flag `-Zregparm=<N>` for X86 (32-bit) for rust-for-linux: https://github.com/rust-lang/rust/issues/116972
Implemented in the similar way as fastcall/vectorcall support (args are marked InReg if fit).
make unsupported_calling_conventions a hard error
This has been a future-compat lint (not shown in dependencies) since Rust 1.55, released 3 years ago. Hopefully that was enough time so this can be made a hard error now. Given that long timeframe, I think it's justified to skip the "show in dependencies" stage. There were [not many crates hitting this](https://github.com/rust-lang/rust/pull/86231#issuecomment-866300943) even when the lint was originally added.
This should get cratered, and I assume then it needs a t-compiler FCP. (t-compiler because this looks entirely like an implementation oversight -- for the vast majority of ABIs, we already have a hard error, but some were initially missed, and we are finally fixing that.)
Fixes https://github.com/rust-lang/rust/pull/87678
Improve test coverage for `unit_bindings` lint
Follow-up to #112380, apparently at the time I didn't add much of any test coverage outside of just "generally works as intended on the test suites and in the crater run".
r? compiler
test: Add test for trait in FQS cast, issue #98565Closes#98565 by adding a test to check for diagnostics when the built-in type `str` is used in a cast where a trait is expected.
stabilize Strict Provenance and Exposed Provenance APIs
Given that [RFC 3559](https://rust-lang.github.io/rfcs/3559-rust-has-provenance.html) has been accepted, t-lang has approved the concept of provenance to exist in the language. So I think it's time that we stabilize the strict provenance and exposed provenance APIs, and discuss provenance explicitly in the docs:
```rust
// core::ptr
pub const fn without_provenance<T>(addr: usize) -> *const T;
pub const fn dangling<T>() -> *const T;
pub const fn without_provenance_mut<T>(addr: usize) -> *mut T;
pub const fn dangling_mut<T>() -> *mut T;
pub fn with_exposed_provenance<T>(addr: usize) -> *const T;
pub fn with_exposed_provenance_mut<T>(addr: usize) -> *mut T;
impl<T: ?Sized> *const T {
pub fn addr(self) -> usize;
pub fn expose_provenance(self) -> usize;
pub fn with_addr(self, addr: usize) -> Self;
pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self;
}
impl<T: ?Sized> *mut T {
pub fn addr(self) -> usize;
pub fn expose_provenance(self) -> usize;
pub fn with_addr(self, addr: usize) -> Self;
pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self;
}
impl<T: ?Sized> NonNull<T> {
pub fn addr(self) -> NonZero<usize>;
pub fn with_addr(self, addr: NonZero<usize>) -> Self;
pub fn map_addr(self, f: impl FnOnce(NonZero<usize>) -> NonZero<usize>) -> Self;
}
```
I also did a pass over the docs to adjust them, because this is no longer an "experiment". The `ptr` docs now discuss the concept of provenance in general, and then they go into the two families of APIs for dealing with provenance: Strict Provenance and Exposed Provenance. I removed the discussion of how pointers also have an associated "address space" -- that is not actually tracked in the pointer value, it is tracked in the type, so IMO it just distracts from the core point of provenance. I also adjusted the docs for `with_exposed_provenance` to make it clear that we cannot guarantee much about this function, it's all best-effort.
There are two unstable lints associated with the strict_provenance feature gate; I moved them to a new [strict_provenance_lints](https://github.com/rust-lang/rust/issues/130351) feature since I didn't want this PR to have an even bigger FCP. ;)
`@rust-lang/opsem` Would be great to get some feedback on the docs here. :)
Nominating for `@rust-lang/libs-api.`
Part of https://github.com/rust-lang/rust/issues/95228.
[FCP comment](https://github.com/rust-lang/rust/pull/130350#issuecomment-2395114536)
Finish stabilization of `result_ffi_guarantees`
The internal linting has been changed, so all that is left is making sure we stabilize what we want to stabilize.
Rollup of 4 pull requests
Successful merges:
- #126588 (Added more scenarios where comma to be removed in the function arg)
- #131728 (bootstrap: extract builder cargo to its own module)
- #131968 (Rip out old effects var handling code from traits)
- #131981 (Remove the `BoundConstness::NotConst` variant)
r? `@ghost`
`@rustbot` modify labels: rollup
Added more scenarios where comma to be removed in the function arg
This is an attempt to address the problem methion in https://github.com/rust-lang/rust/issues/106304#issuecomment-1837273666.
Copy the annotation to explain the fix
If the next Error::Extra ("next") doesn't next to current ("current")
```
fn foo(_: (), _: u32) {}
- foo("current", (), 1u32, "next")
+ foo((), 1u32)
```
If the previous error is not a `Error::Extra`, then do not trim the next comma
```
- foo((), "current", 42u32, "next")
+ foo((), 42u32)
```
Frankly, this is a fix from a test case and may not cover all scenarios
Continue to get rid of `ty::Const::{try_}eval*`
This PR mostly does:
* Removes all of the `try_eval_*` and `eval_*` helpers from `ty::Const`, and replace their usages with `try_to_*`.
* Remove `ty::Const::eval`.
* Rename `ty::Const::normalize` to `ty::Const::normalize_internal`. This function is still used in the normalization code itself.
* Fix some weirdness around the `TransmuteFrom` goal.
I'm happy to split it out further; for example, I could probably land the first part which removes the helpers, or the changes to codegen which are more obvious than the changes to tools.
r? BoxyUwU
Part of https://github.com/rust-lang/rust/issues/130704
`optimize` attribute applied to things other than methods/functions/c…
…losures gives an error (#128488)
Duplicate of #128943, which I had accidentally closed when rebasing.
cc. `@jieyouxu` `@compiler-errors` `@nikomatsakis` `@traviscross` `@pnkfelix.`
compiler: Error on layout of enums with invalid reprs
Surprising no one, the ICEs with the same message have the same root cause.
Invalid reprs can reach layout computation for various reasons. For instance, the compiler may want to use its layout computations to discern if a combination of layout-affecting attributes results in a valid type to begin with by e.g. computing its size. When the input is bad, return an error reflecting that the answer to the question is not a useful one.
Allow `#[deny]` inside `#[forbid]` as a no-op
Forbid cannot be overriden. When someome tries to do this anyways, it results in a hard error. That makes sense.
Except it doesn't, because macros. Macros may reasonably use `#[deny]` (or `#[warn]` for an allow-by-default lint) in their expansion to assert that their expanded code follows the lint. This is doesn't work when the output gets expanded into a `forbid()` context. This is pretty silly, since both the macros and the code agree on the lint!
By making it a warning instead, we remove the problem with the macro, which is now nothing as warnings are suppressed in macro expanded code, while still telling users that something is up.
fixes#121483
Just because the code says it's OK does not mean that it actually is OK.
Nodes with the same total size were not sorted, their order relied on
hashmap iteration.
Stop inverting expectation in normalization errors
We have some funky special case logic to invert the expectation and actual type for normalization errors depending on their cause code. IMO most of the error messages get better, except for `try {}` blocks' type expectations. I think that these need to be special cased in some other way, rather than via this hack.
Fixes#131763
Make sure that outer opaques capture inner opaques's lifetimes even with precise capturing syntax
When lowering an opaque, we must capture and duplicate all of the lifetimes in the opaque's bounds to correctly lower the opaque's bounds. We do this *even if* the lifetime is not captured according to the `+ use<>` precise capturing bound; in that case, we will later reject that captured lifetime. For example, Given an opaque like `impl Sized + 'a + use<>`, we will still duplicate `'a` but later error that it is not mentioned in the `use<>` bound.
The current heuristic was not properly handling cases like:
```
//@ edition: 2024
fn foo<'a>() -> impl Trait<Assoc = impl Trait2> + use<> {}
```
Which forces the outer `impl Trait` to capture `'a` since `impl Trait2` *implicitly* captures `'a` due to the new lifetime capture rules for edition 2024. We were only capturing lifetimes syntactically mentioned in the bounds. (Note that this still is an error; we just need to capture `'a` so it is handled later in the compiler correctly -- hence the ICE in #131769 where a late-bound lifetime was being referenced outside of its binder).
This PR reworks the way we collect lifetimes to capture and duplicate in AST lowering to fix this.
Fixes#131769
warn less about non-exhaustive in ffi
Bindgen allows generating `#[non_exhaustive] #[repr(u32)]` enums. This results in nonintuitive nonlocal `improper_ctypes` warnings, even when the types are otherwise perfectly valid in C.
Adjust for actual tooling expectations by avoiding warning on simple enums with only unit variants.
Closes https://github.com/rust-lang/rust/issues/116831
Forbid cannot be overriden. When someome tries to do this anyways,
it results in a hard error. That makes sense.
Except it doesn't, because macros. Macros may reasonably use `#[deny]`
in their expansion to assert
that their expanded code follows the lint. This is doesn't work when the
output gets expanded into a `forbid()` context. This is pretty silly,
since both the macros and the code agree on the lint!
Therefore, we allow `#[deny(..)]`ing a lint that's already forbidden,
keeping the level at forbid.
Never emit `vptr` for empty/auto traits
Emiting `vptr`s for empty/auto traits is unnecessary (#114942) and causes unsoundness in `trait_upcasting` (#131813). This PR should ensure that we never emit vtables for such traits. See the linked issues for more details.
I'm not sure if I can add tests for the vtable layout. So this PR only adds tests for the soundness hole (i.e., the segmentation fault will disappear after this PR).
Fixes#114942Fixes#131813
Cc #65991 (tracking issue for `trait_upcasting`)
r? `@WaffleLapkin` (per https://github.com/rust-lang/rust/issues/131813#issuecomment-2419969745)
Allow dropping dyn principal
Revival of #126660, which was a revival of #114679. Fixes#126313.
Allows dropping principal when coercing trait objects, e.g. `dyn Debug + Send` -> `dyn Send`.
cc `@compiler-errors` `@Jules-Bertholet`
r? `@lcnr`
Add `must_use` to `CommandExt::exec`
[CommandExt::exec](https://fburl.com/0qhpo7nu) returns a `std::io::Error` in the case exec fails, but its not currently marked as `must_use` making it easy to accidentally ignore it.
This PR adds the `must_use` attributed here as i think it fits the definition in the guide of [When to add #[must_use]](https://std-dev-guide.rust-lang.org/policy/must-use.html#when-to-add-must_use)
Make destructors on `extern "C"` frames to be executed
This would make the example in #123231 print "Noisy Drop". I didn't mark this as fixing the issue because the behaviour is yet to be spec'ed.
Tracking:
- https://github.com/rust-lang/rust/issues/74990
Emscripten: Xfail backtrace ui tests
It is possible to link libunwind and use the normal backtrace code, but it fails to symbolize stack traces. I investigated and could get the list of instruction pointers and symbol names, but I'm not sure how to use the dwarf info to map from instruction pointer to source location. In any case, fixing this is not a high priority.
See https://github.com/rust-lang/rust/issues/131738
r?jieyouxu