Moves the sanitizer ui tests to the sanitizer directory and removes the
sanitizer prefix from tests file names similarly to how the sanitizer
codegen tests are organized.
allow statics pointing to mutable statics
Fixes https://github.com/rust-lang/rust/issues/120450 for good. We can even simplify our checks: no need to specifically go looking for mutable references in const, we can just reject any reference that points to something mutable.
r? `@oli-obk`
Safe Transmute: Revise safety analysis
This PR migrates `BikeshedIntrinsicFrom` to a simplified safety analysis (described [here](https://github.com/rust-lang/project-safe-transmute/issues/15)) that does not rely on analyzing the visibility of types and fields.
The revised analysis treats primitive types as safe, and user-defined types as potentially carrying safety invariants. If Rust gains explicit (un)safe fields, this PR is structured so that it will be fairly easy to thread support for those annotations into the analysis.
Notably, this PR removes the `Context` type parameter from `BikeshedIntrinsicFrom`. Most of the files changed by this PR are just UI tests tweaked to accommodate the removed parameter.
r? `@compiler-errors`
Detect empty leading where clauses on type aliases
1. commit: refactor the AST of type alias where clauses
* I could no longer bear the look of `.0.1` and `.1.0`
* Arguably moving `split` out of `TyAlias` into a substruct might not make that much sense from a semantic standpoint since it reprs an index into `TyAlias.predicates` but it's alright and it cleans up the usage sites of `TyAlias`
2. commit: fix an oversight: An empty leading where clause is still a leading where clause
* semantically reject empty leading where clauses on lazy type aliases
* e.g., on `#![feature(lazy_type_alias)] type X where = ();`
* make empty leading where clauses on assoc types trigger lint `deprecated_where_clause_location`
* e.g., `impl Trait for () { type X where = (); }`
change equate for binders to not rely on subtyping
*summary by `@spastorino` and `@lcnr*`
### Context
The following code:
```rust
type One = for<'a> fn(&'a (), &'a ());
type Two = for<'a, 'b> fn(&'a (), &'b ());
mod my_api {
use std::any::Any;
use std::marker::PhantomData;
pub struct Foo<T: 'static> {
a: &'static dyn Any,
_p: PhantomData<*mut T>, // invariant, the type of the `dyn Any`
}
impl<T: 'static> Foo<T> {
pub fn deref(&self) -> &'static T {
match self.a.downcast_ref::<T>() {
None => unsafe { std::hint::unreachable_unchecked() },
Some(a) => a,
}
}
pub fn new(a: T) -> Foo<T> {
Foo::<T> {
a: Box::leak(Box::new(a)),
_p: PhantomData,
}
}
}
}
use my_api::*;
fn main() {
let foo = Foo::<One>::new((|_, _| ()) as One);
foo.deref();
let foo: Foo<Two> = foo;
foo.deref();
}
```
has UB from hitting the `unreachable_unchecked`. This happens because `TypeId::of::<One>()` is not the same as `TypeId::of::<Two>()` despite them being considered the same types by the type checker.
Currently the type checker considers binders to be equal if subtyping succeeds in both directions: `for<'a> T<'a> eq for<'b> U<'b>` holds if `for<'a> exists<'b> T<'b> <: T'<a> AND for<'b> exists<'a> T<'a> <: T<'b>` holds. This results in `for<'a> fn(&'a (), &'a ())` and `for<'a, 'b> fn(&'a (), &'b ())` being equal in the type system.
`TypeId` is computed by looking at the *structure* of a type. Even though these types are semantically equal, they have a different *structure* resulting in them having different `TypeId`. This can break invariants of unsafe code at runtime and is unsound when happening at compile time, e.g. when using const generics.
So as seen in `main`, we can assign a value of type `Foo::<One>` to a binding of type `Foo<Two>` given those are considered the same type but then when we call `deref`, it calls `downcast_ref` that relies on `TypeId` and we would hit the `None` arm as these have different `TypeId`s.
As stated in https://github.com/rust-lang/rust/issues/97156#issuecomment-1879030033, this causes the API of existing crates to be unsound.
## What should we do about this
The same type resulting in different `TypeId`s is a significant footgun, breaking a very reasonable assumptions by authors of unsafe code. It will also be unsound by itself once they are usable in generic contexts with const generics.
There are two options going forward here:
- change how the *structure* of a type is computed before relying on it. i.e. continue considering `for<'a> fn(&'a (), &'a ())` and `for<'a, 'b> fn(&'a (), &'b ())` to be equal, but normalize them to a common representation so that their `TypeId` are also the same.
- change how the semantic equality of binders to match the way we compute the structure of types. i.e. `for<'a> fn(&'a (), &'a ())` and `for<'a, 'b> fn(&'a (), &'b ())` still have different `TypeId`s but are now also considered to not be semantically equal.
---
Advantages of the first approach:
- with the second approach some higher ranked types stop being equal, even though they are subtypes of each other
General thoughts:
- changing the approach in the future will be breaking
- going from first to second may break ordinary type checking, as types which were previously equal are now distinct
- going from second to first may break coherence, because previously disjoint impls overlap as the used types are now equal
- both of these are quite unlikely. This PR did not result in any crater failures, so this should not matter too much
Advantages of the second approach:
- the soundness of the first approach requires more non-local reasoning. We have to make sure that changes to subtyping do not cause the representative computation to diverge from semantic equality
- e.g. we intend to consider higher ranked implied bounds when subtyping to [fix] https://github.com/rust-lang/rust/issues/25860, I don't know how this will interact and don't feel confident making any prediction here.
- computing a representative type is non-trivial and soundness critical, therefore adding complexity to the "core type system"
---
This PR goes with the second approach. A crater run did not result in any regressions. I am personally very hesitant about trying the first approach due to the above reasons. It feels like there are more unknowns when going that route.
### Changing the way we equate binders
Relating bound variables from different depths already results in a universe error in equate. We therefore only need to make sure that there is 1-to-1 correspondence between bound variables when relating binders. This results in concrete types being structurally equal after anonymizing their bound variables.
We implement this by instantiating one of the binder with placeholders and the other with inference variables and then equating the instantiated types. We do so in both directions.
More formally, we change the typing rules as follows:
```
for<'r0, .., 'rn> exists<'l0, .., 'ln> LHS<'l0, .., 'ln> <: RHS<'r0, .., 'rn>
for<'l0, .., 'ln> exists<'r0, .., 'rn> RHS<'r0, .., 'rn> <: LHS<'l0, .., 'ln>
--------------------------------------------------------------------------
for<'l0, .., 'ln> LHS<'l0, .., 'ln> eq for<'r0, .., 'rn> RHS<'r0, .., 'rn>
```
to
```
for<'r0, .., 'rn> exists<'l0, .., 'ln> LHS<'l0, .., 'ln> eq RHS<'r0, .., 'rn>
for<'l0, .., 'ln> exists<'r0, .., 'rn> RHS<'r0, .., 'rn> eq LHS<'l0, .., 'ln>
--------------------------------------------------------------------------
for<'l0, .., 'ln> LHS<'l0, .., 'ln> eq for<'r0, .., 'rn> RHS<'r0, .., 'rn>
```
---
Fixes#97156
r? `@lcnr`
Count stashed errors again
Stashed diagnostics are such a pain. Their "might be emitted, might not" semantics messes with lots of things.
#120828 and #121206 made some big changes to how they work, improving some things, but still leaving some problems, as seen by the issues caused by #121206. This PR aims to fix all of them by restricting them in a way that eliminates the "might be emitted, might not" semantics while still allowing 98% of their benefit. Details in the individual commit logs.
r? `@oli-obk`
Improve renaming suggestion when item starts with underscore
Fixes https://github.com/rust-lang/rust/issues/121776.
It goes from:
```terminal
error[E0433]: failed to resolve: use of undeclared type `Foo`
--> src/foo.rs:6:13
|
6 | let _ = Foo::Bar;
| ^^^ use of undeclared type `Foo`
|
help: an enum with a similar name exists, consider changing it
|
1 | enum Foo {
| ~~~
```
to:
```terminal
error[E0433]: failed to resolve: use of undeclared type `Foo`
--> foo.rs:6:13
|
6 | let _ = Foo::Bar;
| ^^^ use of undeclared type `Foo`
|
help: an enum with a similar name exists, consider renaming `_Foo` into `Foo`
|
1 | enum Foo {
| ~~~
error: aborting due to 1 previous error
```
Fix `async Fn` confirmation for `FnDef`/`FnPtr`/`Closure` types
Fixes three issues:
1. The code in `extract_tupled_inputs_and_output_from_async_callable` was accidentally getting the *future* type and the *output* type (returned by the future) messed up for fnptr/fndef/closure types. :/
2. We have a (class of) bug(s) in the old solver where we don't really support higher ranked built-in `Future` goals for generators. This is not possible to hit on stable code, but [can be hit with `unboxed_closures`](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=e935de7181e37e13515ad01720bcb899) (#121653).
* I'm opting not to fix that in this PR. Instead, I just instantiate placeholders when confirming `async Fn` goals.
4. Fixed a bug when generating `FnPtr` shims for `async Fn` trait goals.
r? oli-obk
Deeply normalize obligations in `refining_impl_trait`
We somewhat awkwardly use semantic comparison when checking the `refining_impl_trait` lint. This relies on us being able to normalize bounds eagerly to avoid cases where an unnormalized alias is not considered equal to a normalized alias. Since `normalize` in the new solver is a noop, let's use `deeply_normalize` instead.
r? lcnr
cc ``@tmandry,`` this should fix your bug lol
Stashed errors used to be counted as errors, but could then be
cancelled, leading to `ErrorGuaranteed` soundness holes. #120828 changed
that, closing the soundness hole. But it introduced other difficulties
because you sometimes have to account for pending stashed errors when
making decisions about whether errors have occured/will occur and it's
easy to overlook these.
This commit aims for a middle ground.
- Stashed errors (not warnings) are counted immediately as emitted
errors, avoiding the possibility of forgetting to consider them.
- The ability to cancel (or downgrade) stashed errors is eliminated, by
disallowing the use of `steal_diagnostic` with errors, and introducing
the more restrictive methods `try_steal_{modify,replace}_and_emit_err`
that can be used instead.
Other things:
- `DiagnosticBuilder::stash` and `DiagCtxt::stash_diagnostic` now both
return `Option<ErrorGuaranteed>`, which enables the removal of two
`delayed_bug` calls and one `Ty::new_error_with_message` call. This is
possible because we store error guarantees in
`DiagCtxt::stashed_diagnostics`.
- Storing the guarantees also saves us having to maintain a counter.
- Calls to the `stashed_err_count` method are no longer necessary
alongside calls to `has_errors`, which is a nice simplification, and
eliminates two more `span_delayed_bug` calls and one FIXME comment.
- Tests are added for three of the four fixed PRs mentioned below.
- `issue-121108.rs`'s output improved slightly, omitting a non-useful
error message.
Fixes#121451.
Fixes#121477.
Fixes#121504.
Fixes#121508.
This gives one extra error message on two tests, but is necessary to fix
bigger problems caused by the cancellation of stashed errors.
(Note: why not just avoid stashing altogether? Because that resulted in
additional output changes.)
This gives one extra error message on one test, but is necessary to fix
bigger problems caused by the cancellation of stashed errors.
(Note: why not just avoid stashing altogether? Because that resulted in
additional output changes.)
Opportunistically resolve regions when processing region outlives obligations
Due to the matching in `TypeOutlives` being structural, we should attempt to opportunistically resolve regions before processing region obligations. Thanks ``@lcnr`` for finding this.
r? lcnr
Use `LitKind::Err` for malformed floats
#121120 changed `StringReader::cook_lexer_literal` to return `LitKind::Err` for malformed integer literals. This commit does the same for float literals, for consistency.
r? ``@fmease``
Process alias-relate obligations in CoerceUnsized loop
After #119106, we now emit `AliasRelate` goals when relating `?0` and `Alias<T, ..>` in the new solver. In the ad-hoc `CoerceUnsized` selection loop, we now may have `AliasRelate` goals which must be processed to constrain type variables which are mentioned in other goals.
---
For example, in the included test, we try to coerce `&<ManuallyDrop<T> as Deref>::Target` to `&dyn Foo`. This requires proving:
* 1 `&<ManuallyDrop<T> as Deref>::Target: CoerceUnsized<&dyn Foo>`
* 2 `<ManuallyDrop<T> as Deref>::Target alias-relate ?0`
* 3 `?0: Unsize<dyn Foo>`
* 4 `?0: Foo`
* 5 `?0: Sized`
If we don't process goal (2.) before processing goal (3.), then we hit ambiguity since `?0` is never constrained, and therefore we bail out, refusing to coerce the types. After processing (2.), we know `?0 := T`, and the rest of the goals can be processed normally.
Adjust printing for RPITITs
1. Call RPITITs `{synthetic#N}` instead of `{opaque#N}`.
2. Fall back to printing the RPITIT like an opaque even when printed as an `AliasTy`, just like we do for `ty::Alias`.
You could argue that (2.) is misleading, but I believe it's more consistent than naming `{synthetic#N}`, which I assume approximately nobody knows where that def path name comes from.
r? lcnr
unix_sigpipe: Simple fixes and improvements in tests
In https://github.com/rust-lang/rust/pull/120832 I included 5 preparatory commits.
It will take a while before discussions there and in https://github.com/rust-lang/rust/issues/62569 is settled, so here is a PR that splits out 4 of the commits that are easy to review, to get them out of the way.
r? ``@davidtwco`` who already approved these commits in https://github.com/rust-lang/rust/pull/120832 (but I have tweaked them a bit and rebased them since then).
For the convenience of my reviewer, here are the full commit messages of the commits:
<details>
<summary>Click to expand</summary>
```
commit 948b1d68ab (HEAD -> unix_sigpipe-tests-fixes, origin/unix_sigpipe-tests-fixes)
Author: Martin Nordholts <martin.nordholts@codetale.se>
Date: Fri Feb 9 07:57:27 2024 +0100
tests: Add unix_sigpipe-different-duplicates.rs test variant
To make sure that
#[unix_sigpipe = "x"]
#[unix_sigpipe = "y"]
behaves like
#[unix_sigpipe = "x"]
#[unix_sigpipe = "x"]
commit d14f15862d
Author: Martin Nordholts <martin.nordholts@codetale.se>
Date: Fri Feb 9 08:47:47 2024 +0100
tests: Combine unix_sigpipe-not-used.rs and unix_sigpipe-only-feature.rs
The only difference between the files is the presence/absence of
#![feature(unix_sigpipe)]
attribute. Avoid duplication by using revisions instead.
commit a1cb3dba84
Author: Martin Nordholts <martin.nordholts@codetale.se>
Date: Fri Feb 9 06:44:56 2024 +0100
tests: Rename unix_sigpipe.rs to unix_sigpipe-bare.rs for clarity
The test is for the "bare" variant of the attribute that looks like this:
#[unix_sigpipe]
which is not allowed, because it must look like this:
#[unix_sigpipe = "sig_ign"]
commit e060274e55
Author: Martin Nordholts <martin.nordholts@codetale.se>
Date: Fri Feb 9 05:48:24 2024 +0100
tests: Fix typo unix_sigpipe-error.rs -> unix_sigpipe-sig_ign.rs
There is no error expected. It's simply the "regular" test for sig_ign.
So rename it.
```
</details>
Tracking issue: https://github.com/rust-lang/rust/issues/97889
- Put every literal in its own braces, rather than just some of them,
for maximal error recovery.
- Add a blank line between every case, for readability.
This PR stabilizes the `#[diagnostic]` attribute namespace and a minimal
option of the `#[diagnostic::on_unimplemented]` attribute.
The `#[diagnostic]` attribute namespace is meant to provide a home for
attributes that allow users to influence error messages emitted by the
compiler. The compiler is not guaranteed to use any of this hints,
however it should accept any (non-)existing attribute in this namespace
and potentially emit lint-warnings for unused attributes and options.
This is meant to allow discarding certain attributes/options in the
future to allow fundamental changes to the compiler without the need to
keep then non-meaningful options working.
The `#[diagnostic::on_unimplemented]` attribute is allowed to appear
on a trait definition. This allows crate authors to hint the compiler
to emit a specific error message if a certain trait is not implemented.
For the `#[diagnostic::on_unimplemented]` attribute the following
options are implemented:
* `message` which provides the text for the top level error message
* `label` which provides the text for the label shown inline in the
broken code in the error message
* `note` which provides additional notes.
The `note` option can appear several times, which results in several
note messages being emitted. If any of the other options appears several
times the first occurrence of the relevant option specifies the actually
used value. Any other occurrence generates an lint warning. For any
other non-existing option a lint-warning is generated.
All three options accept a text as argument. This text is allowed to
contain format parameters referring to generic argument or `Self` by
name via the `{Self}` or `{NameOfGenericArgument}` syntax. For any
non-existing argument a lint warning is generated.
Tracking issue: #111996
rename 'try' intrinsic to 'catch_unwind'
The intrinsic has nothing to do with `try` blocks, and corresponds to the stable `catch_unwind` function, so this makes a lot more sense IMO.
Also rename Miri's special function while we are at it, to reflect the level of abstraction it works on: it's an unwinding mechanism, on which Rust implements panics.
avoid generalization inside of aliases
The basic idea of this PR is that we don't generalize aliases when the instantiation could fail later on, either due to the *occurs check* or because of a universe error. We instead replace the whole alias with an inference variable and emit a nested `AliasRelate` goal. This `AliasRelate` then fully normalizes the alias before equating it with the inference variable, at which point the alias can be treated like any other rigid type.
We now treat aliases differently depending on whether they are *rigid* or not. To detect whether an alias is rigid we check whether `NormalizesTo` fails. While we already do so inside of `AliasRelate` anyways, also doing so when instantiating a query response would be both ugly/difficult and likely inefficient. To avoid that I change `instantiate_and_apply_query_response` to relate types completely structurally. This change generally removes a lot of annoying complexity, which is nice. It's implemented by adding a flag to `Equate` to change it to structurally handle aliases.
We currently always apply constraints from canonical queries right away. By providing all the necessary information to the canonical query, we can guarantee that instantiating the query response never fails, which further simplifies the implementation. This does add the invariant that *any information which could cause instantiating type variables to fail must also be available inside of the query*.
While it's acceptable for canonicalization to result in more ambiguity, we must not cause the solver to incompletely structurally relate aliases by erasing information. This means we have to be careful when merging universes during canonicalization. As we only generalize for type and const variables we have to make sure that anything nameable by such a type or const variable inside of the canonical query is also nameable outside of it. Because of this we both stop merging universes of existential variables when canonicalizing inputs, we put all uniquified regions into a higher universe which is not nameable by any type or const variable.
I will look into always replacing aliases with inference variables when generalizing in a later PR unless the alias references bound variables. This should both pretty much fix https://github.com/rust-lang/trait-system-refactor-initiative/issues/4. This may allow us to merge the universes of existential variables again by changing generalize to not consider their universe when deciding whether to generalize aliases. This requires some additional non-trivial changes to alias-relate, so I am leaving that as future work.
Fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/79. While it would be nice to decrement universe indices when existing a `forall`, that was surprisingly difficult and not necessary to fix this issue. I am really happy with the approach in this PR think it is the correct way forward to also fix the remaining cases of https://github.com/rust-lang/trait-system-refactor-initiative/issues/8.
Fix more #121208 fallout (round 3)
#121208 converted lots of delayed bugs to bugs. Unsurprisingly, there were a few invalid conversion found via fuzzing.
r? `@lcnr`
Don't unnecessarily change `SIGPIPE` disposition in `unix_sigpipe` tests
In `auxiliary/sigpipe-utils.rs`, all we want to know is the current `SIGPIPE` disposition. We should not change it. So use `libc::sigaction` instead of `libc::signal`. That way we can also remove the code that restores it.
Part of https://github.com/rust-lang/rust/issues/97889.
Split Diagnostics for Uncommon Codepoints: Add Individual Identifier Types
This pull request further modifies the `uncommon_codepoints` lint, adding the individual identifier types of `Technical`, `Not_NFKC`, `Exclusion` and `Limited_Use` to the diagnostic message.
Example rendered diagnostic:
```
error: identifier contains a Unicode codepoint that is not used in normalized strings: 'ij'
--> $DIR/lint-uncommon-codepoints.rs:6:4
|
LL | fn dijkstra() {}
| ^^^^^^^
= note: this character is included in the Not_NFKC Unicode general security profile
```
Second step of #120228.
Prevent cycle in implied predicates computation
Makes #65913 from hang -> fail. I believe fail is the correct state for this test to remain for the long term.
Stabilize `cfg_target_abi`
This stabilizes the `cfg` option called `target_abi`:
```rust
#[cfg(target_abi = "eabihf")]
```
Tracking issue: #80970fixes#78791resolves#80970
In `auxiliary/sigpipe-utils.rs`, all we want to know is the current
`SIGPIPE` disposition. We should not change it. So use `libc::sigaction`
instead of `libc::signal`. That way we can also remove the code that
restores it.
Account for RPITIT in E0310 explicit lifetime constraint suggestion
When given
```rust
trait Original {
fn f() -> impl Fn();
}
trait Erased {
fn f(&self) -> Box<dyn Fn()>;
}
impl<T: Original> Erased for T {
fn f(&self) -> Box<dyn Fn()> {
Box::new(<T as Original>::f())
}
}
```
emit do not emit an invalid suggestion restricting the `Trait::{opaque}` type in a `where` clause:
```
error[E0310]: the associated type `<T as Original>::{opaque#0}` may not live long enough
--> $DIR/missing-static-bound-from-impl.rs:11:9
|
LL | Box::new(<T as Original>::f())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| the associated type `<T as Original>::{opaque#0}` must be valid for the static lifetime...
| ...so that the type `impl Fn()` will meet its required lifetime bounds
```
Partially address #119773. Ideally we'd suggest modifying `Erased::f` instead.
r? `@compiler-errors`
The test is for the "bare" variant of the attribute that looks like this:
#[unix_sigpipe]
which is not allowed, because it must look like this:
#[unix_sigpipe = "sig_ign"]
Don't ICE on anonymous struct in enum variant
Fixes#121446
Computing `adt_def` for the anon struct calls `adt_def` on the parent to find its repr. If the parent is a non-item (e.g. an enum variant) we should have already emitted at least one error, so we just use the repr of the anonymous struct to avoid an ICE.
cc ``@frank-king``
mark `min_exhaustive_patterns` as complete
This is step 1 and 2 of my [proposal](https://github.com/rust-lang/rust/issues/119612#issuecomment-1918097361) to move `min_exhaustive_patterns` forward. The vast majority of in-tree use cases of `exhaustive_patterns` are covered by `min_exhaustive_patterns`. There are a few cases that still require `exhaustive_patterns` in tests and they're all behind references.
r? ``@ghost``
Allow for a missing `adt_def` in `NamePrivacyVisitor`.
This was caused by 72b172bdf6 in #121206. That commit removed an early return from `analysis` when there are stashed errors. As a result, it's possible to reach privacy analysis when there are stashed errors, which means more code paths can be reached. One such code path was handled in that commit, where a `span_bug` was changed to a `span_delayed_bug`.
This commit handles another such code path uncovered by fuzzing, in much the same way.
Fixes#121455.
r? `@oli-obk`
Fix more #121208 fallout
#121208 converted lots of delayed bugs to bugs. Unsurprisingly, there were a few invalid conversion found via fuzzing.
r? `@lcnr`
When encountering `<&T as Clone>::clone(x)` because `T: Clone`, suggest `#[derive(Clone)]`
CC #40699.
```
warning: call to `.clone()` on a reference in this situation does nothing
--> $DIR/noop-method-call.rs:23:71
|
LL | let non_clone_type_ref_clone: &PlainType<u32> = non_clone_type_ref.clone();
| ^^^^^^^^
|
= note: the type `PlainType<u32>` does not implement `Clone`, so calling `clone` on `&PlainType<u32>` copies the reference, which does not do anything and can be removed
help: remove this redundant call
|
LL - let non_clone_type_ref_clone: &PlainType<u32> = non_clone_type_ref.clone();
LL + let non_clone_type_ref_clone: &PlainType<u32> = non_clone_type_ref;
|
help: if you meant to clone `PlainType<u32>`, implement `Clone` for it
|
LL + #[derive(Clone)]
LL | struct PlainType<T>(T);
|
```
Move as many tests from tests/ui/numbers-arithmetic to tests/ui/lint as possible
Fixes#119851 , and also consolidates as many individual tests as possible from numbers-arithmetic. I might have moved the tests in too aggressively, so let me know
Provide suggestions through `rustc_confusables` annotations
Help with common API confusion, like asking for `push` when the data structure really has `append`.
```
error[E0599]: no method named `size` found for struct `Vec<{integer}>` in the current scope
--> $DIR/rustc_confusables_std_cases.rs:17:7
|
LL | x.size();
| ^^^^
|
help: you might have meant to use `len`
|
LL | x.len();
| ~~~
help: there is a method with a similar name
|
LL | x.resize();
| ~~~~~~
```
Fix#59450 (we can open subsequent tickets for specific cases).
Fix#108437:
```
error[E0599]: `Option<{integer}>` is not an iterator
--> f101.rs:3:9
|
3 | opt.flat_map(|val| Some(val));
| ^^^^^^^^ `Option<{integer}>` is not an iterator
|
::: /home/gh-estebank/rust/library/core/src/option.rs:571:1
|
571 | pub enum Option<T> {
| ------------------ doesn't satisfy `Option<{integer}>: Iterator`
|
= note: the following trait bounds were not satisfied:
`Option<{integer}>: Iterator`
which is required by `&mut Option<{integer}>: Iterator`
help: you might have meant to use `and_then`
|
3 | opt.and_then(|val| Some(val));
| ~~~~~~~~
```
On type error of method call arguments, look at confusables for suggestion. Fix#87212:
```
error[E0308]: mismatched types
--> f101.rs:8:18
|
8 | stuff.append(Thing);
| ------ ^^^^^ expected `&mut Vec<Thing>`, found `Thing`
| |
| arguments to this method are incorrect
|
= note: expected mutable reference `&mut Vec<Thing>`
found struct `Thing`
note: method defined here
--> /home/gh-estebank/rust/library/alloc/src/vec/mod.rs:2025:12
|
2025 | pub fn append(&mut self, other: &mut Self) {
| ^^^^^^
help: you might have meant to use `push`
|
8 | stuff.push(Thing);
| ~~~~
```
This was caused by 72b172bdf6 in #121206. That commit removed an early
return from `analysis` when there are stashed errors. As a result, it's
possible to reach privacy analysis when there are stashed errors, which
means more code paths can be reached. One such code path was handled in
that commit, where a `span_bug` was changed to a `span_delayed_bug`.
This commit handles another such code path uncovered by fuzzing, in much
the same way.
Fixes#121455.
remove `sub_relations` from the `InferCtxt`
While doing so, I tried to remove the `delay_span_bug` in `rematch_impl` again, which lead me to discover another `freshen` bug, fixing that one in the second commit. See commit descriptions for the reasoning behind each change.
r? `@compiler-errors`
When given
```rust
trait Original {
fn f() -> impl Fn();
}
trait Erased {
fn f(&self) -> Box<dyn Fn()>;
}
impl<T: Original> Erased for T {
fn f(&self) -> Box<dyn Fn()> {
Box::new(<T as Original>::f())
}
}
```
avoid suggestion to restrict the `Trait::{opaque}` type in a `where` clause:
```
error[E0310]: the associated type `<T as Original>::{opaque#0}` may not live long enough
--> $DIR/missing-static-bound-from-impl.rs:11:9
|
LL | Box::new(<T as Original>::f())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| the associated type `<T as Original>::{opaque#0}` must be valid for the static lifetime...
| ...so that the type `impl Fn()` will meet its required lifetime bounds
```
CC #119773.
Do not provide a structured suggestion when the arguments don't match.
```
error[E0599]: no method named `test_mut` found for struct `Vec<{integer}>` in the current scope
--> $DIR/auto-ref-slice-plus-ref.rs:7:7
|
LL | a.test_mut();
| ^^^^^^^^
|
= help: items from traits can only be used if the trait is implemented and in scope
note: `MyIter` defines an item `test_mut`, perhaps you need to implement it
--> $DIR/auto-ref-slice-plus-ref.rs:14:1
|
LL | trait MyIter {
| ^^^^^^^^^^^^
help: there is a method `get_mut` with a similar name, but with different arguments
--> $SRC_DIR/core/src/slice/mod.rs:LL:COL
```
Consider methods beyond inherent ones when suggesting typos.
```
error[E0599]: no method named `owned` found for reference `&dyn Foo` in the current scope
--> $DIR/object-pointer-types.rs:11:7
|
LL | fn owned(self: Box<Self>);
| --------- the method might not be found because of this arbitrary self type
...
LL | x.owned();
| ^^^^^ help: there is a method with a similar name: `to_owned`
```
Fix#101013.
```
error[E0308]: mismatched types
--> $DIR/rustc_confusables_std_cases.rs:20:14
|
LL | x.append(42);
| ------ ^^ expected `&mut Vec<{integer}>`, found integer
| |
| arguments to this method are incorrect
|
= note: expected mutable reference `&mut Vec<{integer}>`
found type `{integer}`
note: method defined here
--> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL
help: you might have meant to use `push`
|
LL | x.push(42);
| ~~~~
```
Help with common API confusion, like asking for `push` when the data structure really has `append`.
```
error[E0599]: no method named `size` found for struct `Vec<{integer}>` in the current scope
--> $DIR/rustc_confusables_std_cases.rs:17:7
|
LL | x.size();
| ^^^^
|
help: you might have meant to use `len`
|
LL | x.len();
| ~~~
help: there is a method with a similar name
|
LL | x.resize();
| ~~~~~~
```
#59450
No need to `validate_alias_bound_self_from_param_env` in `assemble_alias_bound_candidates`
We already fully normalize the self type before we reach `assemble_alias_bound_candidates`, so there's no reason to double check that a projection is truly rigid by checking param-env bounds.
I think this is also blocked on us making sure to always normalize opaques: #120549.
r? lcnr
Without doing so we use the same candidate cache entry
for `?0: Trait<?1>` and `?0: Trait<?0>`. These goals are different
and we must not use the same entry for them.
we don't track them when canonicalizing or when freshening,
resulting in instable caching in the old solver, and issues when
instantiating query responses in the new one.
Improve codegen diagnostic handling
Clarify the workings of the temporary `Diagnostic` type used to send diagnostics from codegen threads to the main thread.
r? `@estebank`
intrinsics::simd: add missing functions, avoid UB-triggering fast-math
Turns out stdarch declares a bunch more SIMD intrinsics that are still missing from libcore.
I hope I got the docs and in particular the safety requirements right for these "unordered" and "nanless" intrinsics.
Many of these are unused even in stdarch, but they are implemented in the codegen backend, so we may as well list them here.
r? `@Amanieu`
Cc `@calebzulawski` `@workingjubilee`
- Make it more closely match `rustc_errors::Diagnostic`, by making the
field names match, and adding `children`, which requires adding
`rustc_codegen_ssa:🔙:write::Subdiagnostic`.
- Check that we aren't missing important info when converting
diagnostics.
- Add better comments.
- Tweak `rustc_errors::Diagnostic::replace_args` so that we don't need
to do any cloning when converting diagnostics.
Currently `emit_stashed_diagnostic` is called from four(!) different
places: `print_error_count`, `DiagCtxtInner::drop`, `abort_if_errors`,
and `compile_status`.
And `flush_delayed` is called from two different places:
`DiagCtxtInner::drop` and `Queries`.
This is pretty gross! Each one should really be called from a single
place, but there's a bunch of entanglements. This commit cleans up this
mess.
Specifically, it:
- Removes all the existing calls to `emit_stashed_diagnostic`, and adds
a single new call in `finish_diagnostics`.
- Removes the early `flush_delayed` call in `codegen_and_build_linker`,
replacing it with a simple early return if delayed bugs are present.
- Changes `DiagCtxtInner::drop` and `DiagCtxtInner::flush_delayed` so
they both assert that the stashed diagnostics are empty (i.e.
processed beforehand).
- Changes `interface::run_compiler` so that any errors emitted during
`finish_diagnostics` (i.e. late-emitted stashed diagnostics) are
counted and cannot be overlooked. This requires adding
`ErrorGuaranteed` return values to several functions.
- Removes the `stashed_err_count` call in `analysis`. This is possible
now that we don't have to worry about calling `flush_delayed` early
from `codegen_and_build_linker` when stashed diagnostics are pending.
- Changes the `span_bug` case in `handle_tuple_field_pattern_match` to a
`delayed_span_bug`, because it now can be reached due to the removal
of the `stashed_err_count` call in `analysis`.
- Slightly changes the expected output of three tests. If no errors are
emitted but there are delayed bugs, the error count is no longer
printed. This is because delayed bugs are now always printed after the
error count is printed (or not printed, if the error count is zero).
There is a lot going on in this commit. It's hard to break into smaller
pieces because the existing code is very tangled. It took me a long time
and a lot of effort to understand how the different pieces interact, and
I think the new code is a lot simpler and easier to understand.
compiletest: support auxiliaries with auxiliaries
To test behaviour that depends on the extern options of intermediate crates, compiletest auxiliaries must have their own auxiliaries.
Auxiliary compilation previously did not trigger compilation of any auxiliaries in the auxiliary's headers. In addition, those auxiliaries would need to be in an `auxiliary/auxiliary` directory, which is unnecessary and makes some crate graphs harder to write tests for, such as when A depends on B and C, and B depends on C.
For a test `tests/ui/$path/root.rs`, with the following crate graph:
```
root
|-- grandparent
`-- parent
`-- grandparent
```
then the intermediate outputs from compiletest will be:
```
build/$target/test/ui/$path/
|-- auxiliary
| |-- libgrandparent.dylib
| |-- libparent.dylib
| |-- grandparent
| | |-- grandparent.err
| | `-- grandparent.out
| `-- parent
| |-- parent.err
| `-- parent.out
|-- libroot.rmeta
|-- root.err
`-- root.out
```
Support async trait bounds in macros
r? fmease
This is similar to your work on const trait bounds. This theoretically regresses `impl async $ident:ident` in macros, but I doubt this is occurring in practice.
To test behaviour that depends on the extern options of intermediate
crates, compiletest auxiliaries must have their own auxiliaries.
Auxiliary compilation previously did not trigger compilation of any
auxiliaries in the auxiliary's headers. In addition, those auxiliaries
would need to be in an `auxiliary/auxiliary` directory, which is
unnecessary and makes some crate graphs harder to write tests for,
such as when A depends on B and C, and B depends on C.
For a test `tests/ui/$path/root.rs`, with the following crate graph:
```
root
|-- grandparent
`-- parent
`-- grandparent
```
then the intermediate outputs from compiletest will be:
```
build/$target/test/ui/$path/
|-- auxiliary
| |-- libgrandparent.dylib
| |-- libparent.dylib
| |-- grandparent
| | |-- grandparent.err
| | `-- grandparent.out
| `-- parent
| |-- parent.err
| `-- parent.out
|-- libroot.rmeta
|-- root.err
`-- root.out
```
Signed-off-by: David Wood <david@davidtw.co>
Downgrade ambiguous_wide_pointer_comparisons suggestions to MaybeIncorrect
In certain cases like #121330, it is possible to have more than one suggestion from the `ambiguous_wide_pointer_comparisons` lint (which before this PR are `MachineApplicable`). When this gets passed to rustfix, rustfix makes *multiple* changes according to the suggestions which result in incorrect code.
This is a temporary workaround. The real long term solution to problems like these is to address <https://github.com/rust-lang/rust/issues/53934>.
This PR also includes a drive-by edit to the panic message emitted by compiletest because "ui" test suite now uses `//`@`` directives.
Fixes#121330.
Make --verbose imply -Z write-long-types-to-disk=no
When shortening the type it is necessary to take into account the `--verbose` flag, if it is activated, we must always show the entire type and not write it in a file.
Fixes: https://github.com/rust-lang/rust/issues/119130
Convert `delayed_bug`s to `bug`s.
I have a suspicion that quite a few delayed bug paths are impossible to reach, so I did an experiment.
I converted every `delayed_bug` to a `bug`, ran the full test suite, then converted back every `bug` that was hit. A surprising number were never hit.
This is too dangerous to merge. Increased coverage (fuzzing or a crater run) would likely hit more cases. But it might be useful for people to look at and think about which paths are genuinely unreachable.
r? `@ghost`
Fix stray trait mismatch in `resolve_associated_item` for `AsyncFn`
Copy-paste error meant that we were calling `fn_trait_kind_from_def_id` instead of `async_fn_trait_kind_from_def_id`. But turns out we don't even need to do that, since we already matched the trait def id above.
Fixes#121306
r? oli-obk
Don't use raw parameter types in `find_builder_fn`
We shouldn't really ever be using `EarlyBinder::skip_binder` then performing type equality, since param types will never be equal to other types. When checking compatibility with the signature, we instead create some fresh args.
Fixes#121314
Don't ICE when hitting overflow limit in fulfillment loop in next solver
As the title says, let's not ICE when hitting the overflow limit in fulfill. On the other hand, we don't want to treat these as true errors, since it means that whether something is considered a true error or an ambiguity is dependent on overflow handling in the solver, which seems not worth it.
Now that we use the presence of true errors in fulfillment for implicit negative coherence, we especially don't want to tie together coherence and overflow.
I guess I could also drain these errors out of fulfillment and put them into some `ambiguities` storage so we could return them in `select_all_or_error` without having to re-process them every time we call `select_where_possible`. Let me know if that's desired.
r? lcnr
It is possible to have more than one valid suggestion, which when
applied together via rustfix causes the code to no longer compile.
This is a temporary workaround; the real long term solution to these
issues is to solve <https://github.com/rust-lang/rust/issues/53934>.
Trigger `unsafe_code` lint on invocations of `global_asm`
`unsafe_code` already warns about things that don't involve the `unsafe` keyword, e.g. `#[no_mangle]`. This makes it warn on `core::arch::global_asm` too.
Fixes#103078
Use intrinsics::debug_assertions in debug_assert_nounwind
This is the first item in https://github.com/rust-lang/rust/issues/120848.
Based on the benchmarking in this PR, it looks like, for the programs in our benchmark suite, enabling all these additional checks does not introduce significant compile-time overhead, with the single exception of `Alignment::new_unchecked`. Therefore, I've added `#[cfg(debug_assertions)]` to that one call site, so that it remains compiled out in the distributed standard library.
The trailing commas in the previous calls to `debug_assert_nounwind!` were causing the macro to expand to `panic_nouwnind_fmt`, which requires more work to set up its arguments, and that overhead alone is measured between this perf run and the next: https://github.com/rust-lang/rust/pull/120863#issuecomment-1937423502
Always evaluate free constants and statics, even if previous errors occurred
work towards https://github.com/rust-lang/rust/issues/79738
We will need to evaluate static items before the `definitions.freeze()` below, as we will start creating new `DefId`s (for nested allocations) within the `eval_static_initializer` query.
But even without that motivation, this is a good change. Hard errors should always be reported and not silenced if other errors happened earlier.
return `ty::Error` when equating `ty::Error`
This helps iron out a difference in diagnostics between `Sub` and `Equate` relations, which I'm currently trying to unify.
r? oli-obk
Drive-by `DUMMY_SP` -> `Span` and fmt changes
Noticed these while doing something else. There's no practical change, but it's preferable to use `DUMMY_SP` as little as possible, particularly when we have perfectlly useful `Span`s available.
Change leak check and suspicious auto trait lint warning messages
The leak check lint message "this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!" is misleading as some cases may not be phased out and could end being accepted. This is under discussion still.
The suspicious auto trait lint the change in behavior already happened, so the new message is probably more accurate.
r? `@lcnr`
Closes#93367
deduplicate infer var instantiation
Having 3 separate implementations of one of the most subtle parts of our type system is not a good strategy if we want to maintain a sound type system ✨ while working on this I already found some subtle bugs in the existing code, so that's awesome 🎉 cc #121159
This was necessary as I am not confident in my nll changes in #119106, so I am first cleaning this up in a separate PR.
r? `@BoxyUwU`
Noticed these while doing something else. There's no practical change, but it's preferable to use `DUMMY_SP` as little as possible, particularly when we have perfectlly useful `Span`s available.
macro_rules: Preserve all metavariable spans in a global side table
This PR preserves spans of `tt` metavariables used to pass tokens to declarative macros.
Such metavariable spans can then be used in span combination operations like `Span::to` to improve all kinds of diagnostics.
Spans of non-`tt` metavariables are currently kept in nonterminal tokens, but the long term plan is remove all nonterminal tokens from rustc parser and rely on the proc macro model with invisible delimiters (#114647, #67062).
In particular, `NtIdent` nonterminal (corresponding to `ident` metavariables) becomes easy to remove when this PR lands (#119412 does it).
The metavariable spans are kept in a global side table keyed by `Span`s of original tokens.
The alternative to the side table is keeping them in `SpanData` instead, but the performance regressions would be large because any spans from tokens passed to declarative macros would stop being inline and would work through span interner instead, and the penalty would be paid even if we never use the metavar span for the given original span.
(But also see the comment on `fn maybe_use_metavar_location` describing the map collision issues with the side table approach.)
There are also other alternatives - keeping the metavar span in `Token` or `TokenTree`, but associating it with `Span` itsel is the most natural choice because metavar spans are used in span combining operations, and those operations are not necessarily tied to tokens.
Add help to `hir_analysis_unrecognized_intrinsic_function`
To help remind forgetful people like me what step they forgot.
(If this just ICE'd, https://github.com/rust-lang/compiler-team/issues/620 style, the stack trace would point me here, but since there's a "nice" error that information is lost.)
Tracking import use types for more accurate redundant import checking
fixes#117448
By tracking import use types to check whether it is scope uses or the other situations like module-relative uses, we can do more accurate redundant import checking.
For example unnecessary imports in std::prelude that can be eliminated:
```rust
use std::option::Option::Some;//~ WARNING the item `Some` is imported redundantly
use std::option::Option::None; //~ WARNING the item `None` is imported redundantly
```
fixes#117448
For example unnecessary imports in std::prelude that can be eliminated:
```rust
use std::option::Option::Some;//~ WARNING the item `Some` is imported redundantly
use std::option::Option::None; //~ WARNING the item `None` is imported redundantly
```
Rollup of 7 pull requests
Successful merges:
- #120526 (rustdoc: Correctly handle long crate names on mobile)
- #121100 (Detect when method call on argument could be removed to fulfill failed trait bound)
- #121160 (rustdoc: fix and refactor HTML rendering a bit)
- #121198 (Add more checks for `unnamed_fields` during HIR analysis)
- #121218 (Fix missing trait impls for type in rustc docs)
- #121221 (AstConv: Refactor lowering of associated item bindings a bit)
- #121237 (Use better heuristic for printing Cargo specific diagnostics)
r? `@ghost`
`@rustbot` modify labels: rollup
Add more checks for `unnamed_fields` during HIR analysis
Fixes#121151
I also found that we don't prevent enums here so
```rs
#[repr(C)]
#[derive(Debug)]
enum A {
#[default]
B,
C,
}
#[repr(C)]
#[derive(Debug)]
struct D {
_: A,
}
```
leads to an ICE on an `self.is_struct() || self.is_union()` assertion, so fixed that too.
Properly deal with weak alias types as self types of impls
Fixes#114216.
Fixes#116100.
Not super happy about the two ad hoc “normalization” implementations for weak alias types:
1. In `inherent_impls`: The “peeling”, normalization to [“WHNF”][whnf]: Semantically that's exactly what we want (neither proper normalization nor shallow normalization would be correct here). Basically a weak alias type is “nominal” (well...^^) if the WHNF is nominal. [#97974](https://github.com/rust-lang/rust/pull/97974) followed the same approach.
2. In `constrained_generic_params`: Generic parameters are constrained by a weak alias type if the corresp. “normalized” type constrains them (where we only normalize *weak* alias types not arbitrary ones). Weak alias types are injective if the corresp. “normalized” type is injective.
Both have ad hoc overflow detection mechanisms.
**Coherence** is handled in #117164.
r? `@oli-obk` or types
[whnf]: https://en.wikipedia.org/wiki/Lambda_calculus_definition#Weak_head_normal_form
Use fulfillment in next trait solver coherence
Use fulfillment in the new trait solver's `impl_intersection_has_impossible_obligation` routine. This means that inference that falls out of processing other obligations can influence whether we can determine if an obligation is impossible to satisfy. See the committed test.
This should be completely sound, since evaluation and fulfillment both respect intercrate mode equally.
We run the risk of breaking coherence later if we were to change the rules of fulfillment and/or inference during coherence, but this is a problem which affects evaluation, as nested obligations from a trait goal are processed together and can influence each other in the same way.
r? lcnr
cc #114862
Also changed obligationctxt -> fulfillmentctxt because it feels kind of redundant to use an ocx here. I don't really care enough and can change it back if it really matters much.
const_mut_refs: allow mutable pointers to statics
Fixes https://github.com/rust-lang/rust/issues/118447
Writing this PR became a bit messy, see [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/Statics.20pointing.20to.20interior.20mutable.20statics) for some of my journey.^^ Turns out there was a long-standing bug in our qualif logic that led to us incorrectly classifying certain places as "no interior mut" when they actually had interior mut. Due to that the `const_refs_to_cell` feature gate was required far less often than it otherwise would, e.g. in [this code](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=9e0c042c451b3d11d64dd6263679a164). Fixing this however would be a massive breaking change all over libcore and likely the wider ecosystem. So I also changed the const-checking logic to just not require the feature gate for the affected cases. While doing so I discovered a bunch of logic that is not explained and that I could not explain. However I think stabilizing some const-eval feature will make most of that logic inconsequential so I just added some FIXMEs and left it at that.
r? `@oli-obk`
This fixes the issue wherein the lint didn't fire for promoteds
in the case of SHL/SHR operators in non-optimized builds
and all arithmetic operators in optimized builds
we already use `instantiate_const_var`. This does lose some debugging
info for nll because we stop populating the `reg_var_to_origin` table with
`RegionCtxt::Existential(None)`, I don't think that matters however.
Supporting this adds additional complexity to one of the most involved
parts of the type system, so I really don't think it's worth it.
Fix an ICE in the recursion lint
fixes#121170
I looked into it, and there is no good path towards tainting mir_build (where the ICE happens), but using `try_normalize` in a lint seems generally better anyway
allow mutable references in const values when they point to no memory
Fixes https://github.com/rust-lang/rust/issues/120450
The second commit is just some drive-by test suite cleanup.
r? `@oli-obk`
Add clippy into the known `cfg` list
In clippy, we are removing the `feature = "cargo-clippy"` cfg to replace it with `clippy` in https://github.com/rust-lang/rust-clippy/pull/12292. But for it to work, we need to declare `clippy` as cfg. It makes it more coherent with other existing tools like rustdoc.
cc `@flip1995`
Avoid an ICE in diagnostics
fixes#121004
just a slice usage in diagnostics code. Sadly we can't yet bubble the `ErrorGuaranteed` from wf check to borrowck for these cases, as that causes cycle errors iirc