Treat `str` as containing `[u8]` for auto trait purposes
Wanted to gauge ``@rust-lang/lang`` and ``@rust-lang/types`` teams' thoughts on treating `str` as "containing" a `[u8]` slice for auto-trait purposes.
``@dtolnay`` brought this up in https://github.com/rust-lang/rust/issues/13231#issuecomment-1399386472 as a blocker for future `str` type librarification, and I think it's both a valid concern and very easy to fix. I'm interested in actually doing that `str` type librarification (#107939), but this probably should be considered in the mean time regardless of that PR.
r? types for the impl, though this definitely needs an FCP.
Rollup of 8 pull requests
Successful merges:
- #107062 (Do some cleanup of doc/index.md)
- #107890 (Lint against `Iterator::map` receiving a callable that returns `()`)
- #108431 (Add regression test for #107918)
- #108432 (test: drop unused deps)
- #108436 (make "proc macro panicked" translatable)
- #108444 (docs/test: add UI test and docs for `E0476`)
- #108449 (Do not lint ineffective unstable trait impl for unresolved trait)
- #108456 (Complete migrating `ast_passes` to derive diagnostics)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
docs/test: add UI test and docs for `E0476`
Final undocumented error code. Not entirely sure about wording in the docs.
Part of https://github.com/rust-lang/rust/issues/61137.
r? ```@compiler-errors```
cc ```@compiler-errors```
Implement -Zlink-directives=yes/no
`-Zlink-directives=no` will ignored `#[link]` directives while compiling a crate, so nothing is emitted into the crate's metadata. The assumption is that the build system already knows about the crate's native dependencies and can provide them at link time without these directives.
This is another way to address issue # #70093, which is currently addressed by `-Zlink-native-libraries` (implemented in #70095). The latter is implemented at link time, which has the effect of ignoring `#[link]` in *every* crate. This makes it a very large hammer as it requires all native dependencies to be known to the build system to be at all usable, including those in sysroot libraries. I think this means its effectively unused, and definitely under-used.
Being able to control this on a crate-by-crate basis should make it much easier to apply when needed.
I'm not sure if we need both mechanisms, but we can decide that later.
cc `@pcwalton` `@cramertj`
diagnostics: remove inconsistent English article "this" from E0107
Consider [`tests/ui/const-generics/generic_const_exprs/issue-102768.stderr`][issue-102768.stderr], the error message where it gives additional notes about where the associated type is defined, and how the dead code lint doesn't have an article, like in [`tests/ui/lint/dead-code/issue-85255.stderr`][issue-85255.stderr]. They don't have articles, so it seems unnecessary to have one here.
[issue-102768.stderr]: 07c993eba8/tests/ui/const-generics/generic_const_exprs/issue-102768.stderr
[issue-85255.stderr]: 07c993eba8/tests/ui/lint/dead-code/issue-85255.stderr
parser: provide better suggestions and errors on closures with braces missing
We currently provide wrong suggestions and unhelpful errors on closure bodies with braces missing.
For example, given the following code:
```rust
fn main() {
let _x = Box::new(|x|x+1;);
}
```
the current output is:
```
error: expected expression, found `)`
--> ./main.rs:2:30
|
2 | let _x = Box::new(|x|x+1;);
| ^ expected expression
error: closure bodies that contain statements must be surrounded by braces
--> ./main.rs:2:25
|
2 | let _x = Box::new(|x|x+1;);
| ^
3 | }
| ^
|
note: statement found outside of a block
--> ./main.rs:2:29
|
2 | let _x = Box::new(|x|x+1;);
| ---^ this `;` turns the preceding closure into a statement
| |
| this expression is a statement because of the trailing semicolon
note: the closure body may be incorrectly delimited
--> ./main.rs:2:23
|
2 | let _x = Box::new(|x|x+1;);
| ^^^^^^ this is the parsed closure...
3 | }
| - ...but likely you meant the closure to end here
help: try adding braces
|
2 ~ let _x = Box::new(|x| {x+1;);
3 ~ }}
|
error: expected `;`, found `}`
--> ./main.rs:2:32
|
2 | let _x = Box::new(|x|x+1;);
| ^ help: add `;` here
3 | }
| - unexpected token
error: aborting due to 3 previous errors
```
We got 3 errors, but all but the second are unnecessary or just wrong.
This commit allows outputting correct suggestions and errors. The above code would output like this:
```
error: closure bodies that contain statements must be surrounded by braces
--> ./main.rs:2:25
|
2 | let _x = Box::new(|x|x+1;);
| ^ ^
|
note: statement found outside of a block
--> ./main.rs:2:29
|
2 | let _x = Box::new(|x|x+1;);
| ---^ this `;` turns the preceding closure into a statement
| |
| this expression is a statement because of the trailing semicolon
note: the closure body may be incorrectly delimited
--> ./main.rs:2:23
|
2 | let _x = Box::new(|x|x+1;);
| ^^^^^^ - ...but likely you meant the closure to end here
| |
| this is the parsed closure...
help: try adding braces
|
2 | let _x = Box::new(|x| {x+1;});
| + +
error: aborting due to previous error
```
Fixes https://github.com/rust-lang/rust/issues/107959.
r? diagnostics
Fix ICE in 'duplicate diagnostic item' diagnostic
Not sure how to add this in a test; I found it by mistakenly running `cargo fix --lib -p std` rather than `x fix` at the root.
Add test for bad cast with deferred projection equality
1. Unification during coercion (`Coerce::unify`) needs to consider deferred projection obligations (at least pass over them with `predicate_may_hold` or something, to disqualify any totally wrong unifications) -- otherwise, we'll shallowly consider `<u8 as Add>::Output` and `char` as coercible during `FnCtxt::try_coerce`, which will fail later when the nested obligations are registered and processed.
2. Cast checking needs to be able to structurally normalize types so it sees `u8` instead of `<u8 as Add>::Output`. Otherwise it'll always consider the latter as part of a non-primitive cast. Currently `FnCtxt::normalize` doesn't do anything useful here, interestingly.
I tried looking into both of these and it's not immediately clear where to refactor existing typeck code to fix this (at least the latter), but I'm gonna commit a test for it at least so we don't forget. This is one of the issues that's keeping us from building larger projects.
implement const iterator using `rustc_do_not_const_check`
Previous experiment: #102225.
Explanation: rather than making all default methods work under `const` all at once, this uses `rustc_do_not_const_check` as a workaround to "trick" the compiler to not run any checks on those other default methods. Any const implementations are only required to implement the `next` method. Any actual calls to the trait methods other than `next` will either error in compile time (at CTFE runs), or run the methods correctly if they do not have any non-const operations. This is extremely easy to maintain, remove, or improve.
Consider `tests/ui/const-generics/generic_const_exprs/issue-102768.stderr`,
the error message where it gives additional notes about where the associated
type is defined, and how the dead code lint doesn't have an article,
like in `tests/ui/lint/dead-code/issue-85255.stderr`. They don't have
articles, so it seems unnecessary to have one here.
We currently provide wrong suggestions and unhelpful errors on closure
bodies with braces missing. For example, given the following code:
```
fn main() {
let _x = Box::new(|x|x+1;);
}
```
the current output is like this:
```
error: expected expression, found `)`
--> ./main.rs:2:30
|
2 | let _x = Box::new(|x|x+1;);
| ^ expected expression
error: closure bodies that contain statements must be surrounded by braces
--> ./main.rs:2:25
|
2 | let _x = Box::new(|x|x+1;);
| ^
3 | }
| ^
|
...
help: try adding braces
|
2 ~ let _x = Box::new(|x| {x+1;);
3 ~ }}
...
error: expected `;`, found `}`
--> ./main.rs:2:32
|
2 | let _x = Box::new(|x|x+1;);
| ^ help: add `;` here
3 | }
| - unexpected token
error: aborting due to 3 previous errors
```
This commit allows outputting correct suggestions and errors. The above
code would output like this:
```
error: closure bodies that contain statements must be surrounded by braces
--> ./main.rs:2:25
|
2 | let _x = Box::new(|x|x+1;);
| ^ ^
|
note: statement found outside of a block
--> ./main.rs:2:29
|
2 | let _x = Box::new(|x|x+1;);
| ---^ this `;` turns the preceding closure into a statement
| |
| this expression is a statement because of the trailing semicolon
note: the closure body may be incorrectly delimited
--> ./main.rs:2:23
|
2 | let _x = Box::new(|x|x+1;);
| ^^^^^^ - ...but likely you meant the closure to end here
| |
| this is the parsed closure...
help: try adding braces
|
2 | let _x = Box::new(|x| {x+1;});
| + +
error: aborting due to previous error
```
Ban associated type bounds in bad positions
We should not try to lower associated type bounds into TAITs in positions where `impl Trait` is not allowed (except for in `where` clauses, like `where T: Trait<Assoc: Bound>`).
This is achieved by using the same `rustc_ast_lowering` machinery as impl-trait does to characterize positions as universal/existential/disallowed.
Fixes#106077
Split out the first commit into #108066, since it's not really related.
Lint dead code in closures and generators
Fixes#108296
I think this might be a potentially breaking change, but restores the behaviour of pre-1.64.
`@rustbot` label +A-lint
Don't delay `ReError` bug during lexical region resolve
Lexical region resolution returns a list of `RegionResolutionError` which don't necessarily correspond to diagnostics being emitted. The compiler may, validly, throw away these resolution errors and do something else. Therefore it's not valid to use `ReError` during lifetime resolution, since we may actually be on a totally fine compilation path.
For example, the `implied_bounds_entailment` lint runs region resolution twice, and only emits an error if it fails both times. If we delay a bug and create a `ReError` during this first run, then we will ICE.
Fixes#108170
----
Side-note: this is conceptually equivalent to how we can't necessarily delay bugs or create `ty::Error` during trait solving/fulfillment, since the compiler is allowed to throw away these fulfillment errors to do other things. It's only once we actually emit an error (`report_region_errors` / `report_fulfillment_errors`)
`-Zlink-directives=no` will ignored `#[link]` directives while compiling a
crate, so nothing is emitted into the crate's metadata. The assumption is
that the build system already knows about the crate's native dependencies
and can provide them at link time without these directives.
This is another way to address issue # #70093, which is currently addressed
by `-Zlink-native-libraries` (implemented in #70095). The latter is
implemented at link time, which has the effect of ignoring `#[link]`
in *every* crate. This makes it a very large hammer as it requires all
native dependencies to be known to the build system to be at all usable,
including those in sysroot libraries. I think this means its effectively
unused, and definitely under-used.
Being able to control this on a crate-by-crate basis should make it much
easier to apply when needed.
I'm not sure if we need both mechanisms, but we can decide that later.
Fix overlapping spans in removing extra arguments
Fixes#108225
Each span is already extended to include the previous comma, so extending to the *next* comma is unecessary and causes an ICE with assertions on.
``@rustbot`` label +A-diagnostics
Convert a hard-warning about named static lifetimes into lint "unused_lifetimes"
Fixes https://github.com/rust-lang/rust/issues/96956.
Some changes are ported from https://github.com/rust-lang/rust/pull/98079, thanks to jeremydavis519.
r? `@estebank` `@petrochenkov`
Any feedback is appreciated!
## Actions
- [x] resolve conflicts
- [x] fix build
- [x] address review comments in last pr
- [x] update tests
Define the `named_static_lifetimes` lint
This lint will replace the existing hard-warning.
Replace the named static lifetime hard-warning with the new lint
Update the UI tests for the `named_static_lifetimes` lint
Remove the direct dependency on `rustc_lint_defs`
fix build
Signed-off-by: Zhi Qi <qizhi@pingcap.com>
use "UNUSED_LIFETIMES" instead
Signed-off-by: Zhi Qi <qizhi@pingcap.com>
update 1 test and fix typo
Signed-off-by: Zhi Qi <qizhi@pingcap.com>
update tests
Signed-off-by: Zhi Qi <qizhi@pingcap.com>
fix tests: add extra blank line
Signed-off-by: Zhi Qi <qizhi@pingcap.com>
Use DefKind to give more item kind information during BindingObligation note
The current label says "required by a bound in this". When I see that label, my immediate impression is "this... **what**?". It feels like it was cut short.
Alternative to this would be saying "in this item", but adding the item kind is strictly more informational and adds very little overhead to the existing error presentation.
Make hidden type registration opt-in, so that each site can be reviewed on its own and we have the right defaults for trait solvers
r? `@lcnr`
pulled out of https://github.com/rust-lang/rust/pull/107891 as it is the uncontroversial part
Move `Fn*` traits malformedness protections to typeck
I found it strange that we were doing a custom well-formedness check just for the `Fn*` traits' `call_*` fn items. My understanding from the git history is that this is just to avoid ICEs later on in typeck.
Well, that well-formedness check isn't even implemented correctly for `FnOnce::call_once`, or `FnMut::call_mut` for that matter. Instead, this PR just makes the typeck checks more robust, and leaves it up to the call-site to report errors when lang items are implemented in funny ways.
This coincidentally fixes another ICE where a the `Add` lang item is implemented with a `add` item that's a const instead of a method.
Add a test for default trait method with RPITITs
This didn't work in #107013, but now that #108203 has landed, let's make sure we don't regress it.
r? types
Name placeholder in some region errors
Also don't print `ReVar` or `ReLateBound` as debug... these error messages are super uncommon anyways, but in the case they do trigger, let's be slightly more helpful.
lint: don't suggest MaybeUninit::assume_init for uninhabited types
Creating a zeroed uninhabited type such as `!` or an empty enum with `mem::zeroed()` (or transmuting `()` to `!`) currently triggers this lint:
```rs
warning: the type `!` does not permit zero-initialization
--> test.rs:5:23
|
5 | let _val: ! = mem::zeroed();
| ^^^^^^^^^^^^^
| |
| this code causes undefined behavior when executed
| help: use `MaybeUninit<T>` instead, and only call `assume_init` after initialization is done
|
= note: the `!` type has no valid value
```
The `MaybeUninit` suggestion in the help message seems confusing/useless for uninhabited types, as such a type cannot be fully initialized in the first place (as the note implies).
This PR limits this help message to inhabited types which can be initialized
Miri: basic dyn* support
As usual I am very unsure about the dynamic dispatch stuff, but it passes even the `Pin<&mut dyn* Trait>` test so that is something.
TBH I think it was a mistake to make `dyn Trait` and `dyn* Trait` part of the same `TyKind` variant. Almost everywhere in Miri this lead to the wrong default behavior, resulting in strange ICEs instead of nice "unimplemented" messages. The two types describe pretty different runtime data layout after all.
Strangely I did not need to do the equivalent of [this diff](https://github.com/rust-lang/rust/pull/106532#discussion_r1087095963) in Miri. Maybe that is because the unsizing logic matches on `ty::Dynamic(.., ty::Dyn)` already? In `unsized_info` I don't think the `target_dyn_kind` can be `DynStar`, since then it wouldn't be unsized!
r? `@oli-obk` Cc `@eholk` (dyn-star) https://github.com/rust-lang/rust/issues/102425
Refine error span for trait error into borrowed expression
Extends the error span refinement in #106477 to drill into borrowed expressions just like tuples/struct/enum literals. For example,
```rs
trait Fancy {}
trait Good {}
impl <'a, T> Fancy for &'a T where T: Good {}
impl <S> Good for Option<S> where S: Iterator {}
fn want_fancy<F>(f: F) where F: Fancy {}
fn example() {
want_fancy(&Some(5));
// (BEFORE) ^^^^^^^^ `{integer}` is not an iterator
// (AFTER) ^ `{integer}` is not an iterator
}
```
Existing heuristics try to find the right part of the expression to "point at"; current heuristics look at e.g. struct constructors and tuples. This PR adds a new check for borrowed expressions when looking into a borrowed type.
Use restricted Damerau-Levenshtein distance for diagnostics
This replaces the existing Levenshtein algorithm with the Damerau-Levenshtein algorithm. This means that "ab" to "ba" is one change (a transposition) instead of two (a deletion and insertion). More specifically, this is a _restricted_ implementation, in that "ca" to "abc" cannot be performed as "ca" → "ac" → "abc", as there is an insertion in the middle of a transposition. I believe that errors like that are sufficiently rare that it's not worth taking into account.
This was first brought up [on IRLO](https://internals.rust-lang.org/t/18227) when it was noticed that the diagnostic for `prinltn!` (transposed L and T) was `print!` and not `println!`. Only a single existing UI test was effected, with the result being an objective improvement.
~~I have left the method name and various other references to the Levenshtein algorithm untouched, as the exact manner in which the edit distance is calculated should not be relevant to the caller.~~
r? ``@estebank``
``@rustbot`` label +A-diagnostics +C-enhancement
create dummy placeholder crate to prevent compiler from panicing
This PR is to address the panic found in https://github.com/rust-lang/rust/issues/105700.
There are 2 separate things going on with this panic.
First the code could not generate a dummy response for crate fragment types when it hits the recursion limit.
This PR adds the method to the trait implementation for `DymmyResult` to be able to create a dummy crate node.
This stops the panic from happening.
The second thing that is not addressed (and maybe does not need addressing? 🤷🏻)
is that when you have multiple attributes it ends up treating attributes that follow another as being the result of expanding the former (maybe there is a better way to say that). So you end up hitting the recursion limit. Even though you would think there is no expansion happening here.
If you did not hit the recursion limit the compiler would output that `invalid_attribute` does not exists. But it currently exits before the resolution step when the recursion limit is reached here.
Type-directed probing for inherent associated types
When probing for inherent associated types (IATs), equate the Self-type found in the projection with the Self-type of the relevant inherent impl blocks and check if all predicates are satisfied.
Previously, we didn't look at the Self-type or at the bounds and just picked the first inherent impl block containing an associated type with the name we were searching for which is obviously incorrect.
Regarding the implementation, I basically copied what we do during method probing (`assemble_inherent_impl_probe`, `consider_probe`). Unfortunately, I had to duplicate a lot of the diagnostic code found in `rustc_hir_typeck::method::suggest` which we don't have access to in `rustc_hir_analysis`. Not sure if there is a simple way to unify the error handling. Note that in the future, `rustc_hir_analysis::astconv` might not actually be the place where we resolve inherent associated types (see https://github.com/rust-lang/rust/pull/103621#issuecomment-1304309565) but `rustc_hir_typeck` (?) in which case the duplication may naturally just disappear. While inherent associated *constants* are currently resolved during "method" probing, I did not find a straightforward way to incorporate IAT lookup into it as types and values (functions & constants) are two separate entities for which distinct code paths are taken.
Fixes#104251 (incl. https://github.com/rust-lang/rust/issues/104251#issuecomment-1338501171).
Fixes#105305.
Fixes#107468.
`@rustbot` label T-types F-inherent_associated_types
r? types