Don't ICE in `might_permit_raw_init` if reference is polymorphic
Emitting optimized MIR for a polymorphic function may require computing layout of a type that isn't (yet) known. This happens in the instcombine pass, for example. Let's fail gracefully in that condition.
cc `@saethlin`
fixes#107999
Don't suggest `#[doc(hidden)]` trait methods with matching return type
Fixes#107983, addressing the bad suggestion.
The test can probably be made more specific to this case, but I'm unsure how.
`@rustbot` label +A-diagnostics
Fix unintentional UB in ui tests
`@matthiaskrgr` found UB in a bunch of the ui tests. This PR fixes a batch of miscellaneous tests I didn't think needed reviewers from a particular part of the project.
Avoid accessing HIR when it can be avoided
Experiment to see if it helps some incremental cases.
Will be rebased once https://github.com/rust-lang/rust/pull/107942 gets merged.
r? `@ghost`
Rollup of 7 pull requests
Successful merges:
- #105300 (rework min_choice algorithm of member constraints)
- #107163 (Remove some superfluous type parameters from layout.rs.)
- #107173 (Suggest the correct array length on mismatch)
- #107411 (Handle discriminant in DataflowConstProp)
- #107968 (Enable `#[thread_local]` on armv6k-nintendo-3ds)
- #108032 (Un📦ing the Resolver)
- #108060 (Revert to using `RtlGenRandom` as a fallback)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Suggest the correct array length on mismatch
Fixes#107156
I wasn't able to find a way to get the `Span` for the actual array size unfortunately, so this suggestion can't be applied automatically.
``@rustbot`` label +A-diagnostics
rework min_choice algorithm of member constraints
See [this comment](https://github.com/rust-lang/rust/pull/105300#issuecomment-1384312743) for the description of the new algorithm.
Fixes#63033Fixes#104639
This uses a more general algorithm than #89056 that doesn't treat `'static` as a special case. It thus accepts more code. For example:
```rust
async fn test2<'s>(_: &'s u8, _: &'_ &'s u8, _: &'_ &'s u8) {}
```
I claim it's more correct as well because it fixes#104639.
cc ``@nikomatsakis`` ``@lqd`` ``@tmandry`` ``@eholk`` ``@chenyukang`` ``@oli-obk``
r? types
use semantic equality for const param type equality assertion
Fixes#107898
See added test for what caused this ICE
---
The current in assertion in `relate.rs` is rather inadequate when keeping in mind future expansions to const generics:
- it will ICE when there are infer vars in a projection in a const param ty
- it will spurriously return false when either ty has infer vars because of using `==` instead of `infcx.at(..).eq`
- i am also unsure if it would be possible with `adt_const_params` to craft a situation where the const param type is not wf causing `normalize_erasing_regions` to `bug!` when we would have emitted a diagnostic.
This impl feels pretty Not Great to me although i am not sure what a better idea would be.
- We have to have the logic behind a query because neither `relate.rs` or `combine.rs` have access to trait solving machinery (without evaluating nested obligations this assert will become _far_ less useful under lazy norm, which consts are already doing)
- `relate.rs` does not have access to canonicalization machinery which is necessary in order to have types potentially containing infer vars in query arguments.
We could possible add a method to `TypeRelation` to do this assertion rather than a query but to avoid implementing the same logic over and over we'd probably end up with the logic in a free function somewhere in `rustc_trait_selection` _anyway_ so I don't think that would be much better.
We could also just remove this assertion, it should not actually be necessary for it to be present. It has caught some bugs in the past though so if possible I would like to keep it.
r? `@compiler-errors`
add an unstable `#[rustc_coinductive]` attribute
useful to test coinduction, especially in the new solver.
as this attribute should remain permanently unstable I don't think this needs any official approval. cc ``@rust-lang/types``
had to weaken the check for stable query results in the solver to prevent an ICE if there's a coinductive cycle with constraints.
r? ``@compiler-errors``
Update the minimum external LLVM to 14
With this change, we'll have stable support for LLVM 14 through 16 (pending release).
For reference, the previous increase to LLVM 13 was #100460.
Suggest fix for misplaced generic params on fn item #103366fixes#103366
This still has some work to go, but works for 2/3 of the initial base cases described in #1033366
simple fn:
```
error: expected identifier, found `<`
--> shreys/test_1.rs:1:3
|
1 | fn<T> id(x: T) -> T { x }
| ^ expected identifier
|
help: help: place the generic parameter list after the function name:
|
1 | fn id<T>(x: T) -> T { x }
| ~~~~
```
Complicated bounds
```
error: expected identifier, found `<`
--> spanishpear/test_2.rs:1:3
|
1 | fn<'a, B: 'a + std::ops::Add<Output = u32>> f(_x: B) { }
| ^ expected identifier
|
help: help: place the generic parameter list after the function name:
|
1 | fn f<'a, B: 'a + std::ops::Add<Output = u32>>(_x: B) { }
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```
Opening a draft PR for comments on approach, particularly I have the following questions:
- [x] Is it okay to be using `err.span_suggestion` over struct derives? I struggled to get the initial implementation (particularly the correct suggestion message) on struct derives, although I think given what I've learned since starting, I could attempt re-doing it with that approach.
- [x] in the case where the snippet cannot be obtained from a span, is the `help` but no suggestion okay? I think yes (also, when does this case occur?)
- [x] are there any red flags for the generalisation of this work for relevant item kinds (i.e. `struct`, `enum`, `trait`, and `union`). My basic testing indicates it does work for those types except the help tip is currently hardcoded to `after the function name` - which should change dependent on the item.
- [x] I am planning to not show the suggestion if there is already a `<` after the item identifier, (i.e. if there are already generics, as after a function name per the original issue). Any major objections?
- [x] Is the style of error okay? I wasn't sure if there was a way to make it display nicer, or if thats handled by span_suggestion
These aren't blocking questions, and I will keep working on:
- check if there is a `<` after the ident (and if so, not showing the suggestion)
- generalize the help message
- figuring out how to write/run/etc ui tests (including reading the docs for them)
- logic cleanups
Note that at the time of this commit, `unic-emoji-char` seems to have
data tables only up to Unicode 5.0, but Unicode is already newer than
this.
A newer emoji such as `🥺` will not be recognized as an emoji
but older emojis such as `🐱` will.
fix: improve the suggestion on future not awaited
Considering the following code
```rust
fn foo() -> u8 {
async fn async_fn() -> u8 { 22 }
async_fn()
}
fn main() {}
```
the error generated before this commit from the compiler is
```
➜ rust git:(macros/async_fn_suggestion) ✗ rustc test.rs --edition 2021
error[E0308]: mismatched types
--> test.rs:4:5
|
1 | fn foo() -> u8 {
| -- expected `u8` because of return type
...
4 | async_fn()
| ^^^^^^^^^^ expected `u8`, found opaque type
|
= note: expected type `u8`
found opaque type `impl Future<Output = u8>`
help: consider `await`ing on the `Future`
|
4 | async_fn().await
| ++++++
error: aborting due to previous error
```
In this case the error is nor perfect, and can confuse the user that do not know that the opaque type is the future.
So this commit will propose (and conclude the work start in https://github.com/rust-lang/rust/issues/80658)
to change the string `opaque type` to `future` when applicable and also remove the Expected vs Received note by adding a more specific one regarding the async function that return a future type.
So the new error emitted by the compiler is
```
error[E0308]: mismatched types
--> test.rs:4:5
|
1 | fn foo() -> u8 {
| -- expected `u8` because of return type
...
4 | async_fn()
| ^^^^^^^^^^ expected `u8`, found future
|
note: calling an async function returns a future
--> test.rs:4:5
|
4 | async_fn()
| ^^^^^^^^^^
help: consider `await`ing on the `Future`
|
4 | async_fn().await
| ++++++
error: aborting due to previous error
```
Fixes https://github.com/rust-lang/rust/issues/80658
It remains to rework the case described in the following issue https://github.com/rust-lang/rust/issues/107899 but I think this deserves its own PR after we discuss a little bit how to handle these kinds of cases.
r? `@eholk`
`@rustbot` label +I-async-nominated
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
Move folding & visiting traits into type library
This is a rework of #107712, following feedback on that PR.
In particular, this version uses trait aliases to reduce the API churn for trait consumers. Doing so requires a workaround for #107747 until its fix in #107803 is merged into the stage0 compiler; this workaround, which uses conditional compilation based on the `bootstrap` configuration predicate, sits in dedicated commit b409329c for ease of reversion.
The possibility of the `rustc_middle` crate retaining its own distinct versions of each folding/visiting trait, blanket-implemented on all types that implement the respective trait in the type library, was also explored: however since this would necessitate making each `rustc_middle` trait a subtrait of the respective type library trait (so that such blanket implementations can delegate their generic methods), no benefit would be gained.
r? types
Considering the following code
```rust
fn foo() -> u8 {
async fn async_fn() -> u8 { 22 }
async_fn()
}
fn main() {}
```
the error generated before this commit from the compiler is
```
➜ rust git:(macros/async_fn_suggestion) ✗ rustc test.rs --edition 2021
error[E0308]: mismatched types
--> test.rs:4:5
|
1 | fn foo() -> u8 {
| -- expected `u8` because of return type
...
4 | async_fn()
| ^^^^^^^^^^ expected `u8`, found opaque type
|
= note: expected type `u8`
found opaque type `impl Future<Output = u8>`
help: consider `await`ing on the `Future`
|
4 | async_fn().await
| ++++++
error: aborting due to previous error
```
In this case the error is nor perfect, and can confuse the user
that do not know that the opaque type is the future.
So this commit will propose (and conclude the work start in
https://github.com/rust-lang/rust/issues/80658)
to change the string `opaque type` to `future` when applicable
and also remove the Expected vs Received note by adding a more
specific one regarding the async function that return a future type.
So the new error emitted by the compiler is
```
error[E0308]: mismatched types
--> test.rs:4:5
|
1 | fn foo() -> u8 {
| -- expected `u8` because of return type
...
4 | async_fn()
| ^^^^^^^^^^ expected `u8`, found future
|
note: calling an async function returns a future
--> test.rs:4:5
|
4 | async_fn()
| ^^^^^^^^^^
help: consider `await`ing on the `Future`
|
4 | async_fn().await
| ++++++
error: aborting due to previous error
```
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
Introduce `-Zterminal-urls` to use OSC8 for error codes
Terminals supporting the OSC8 Hyperlink Extension can support inline anchors where the text is user defineable but clicking on it opens a browser to a specified URLs, just like `<a href="URL">` does in HTML.
https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
Enable new rlib in non stable cases
If bundled static library uses cfg (unstable) or whole-archive (wasn't supported) bundled libs are packed even without packed_bundled_libs.
r? `@petrochenkov`
simplify layout calculations in rawvec
The use of `Layout::array` was introduced in #83706 which lead to a [perf regression](https://github.com/rust-lang/rust/pull/83706#issuecomment-1048377719).
This PR basically reverts that change since rust currently only supports stride == size types, but to be on the safe side it leaves a const-assert there to make sure this gets caught if those assumptions ever change.
Rollup of 9 pull requests
Successful merges:
- #105019 (Add parentheses properly for borrowing suggestion)
- #106001 (Stop at the first `NULL` argument when iterating `argv`)
- #107098 (Suggest function call on pattern type mismatch)
- #107490 (rustdoc: remove inconsistently-present sidebar tooltips)
- #107855 (Add a couple random projection tests for new solver)
- #107857 (Add ui test for implementation on projection)
- #107878 (Clarify `new_size` for realloc means bytes)
- #107888 (revert #107074, add regression test)
- #107900 (Zero the `REPARSE_MOUNTPOINT_DATA_BUFFER` header)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Implement `deferred_projection_equality` for erica solver
Somewhat of a revival of #96912. When relating projections now emit an `AliasEq` obligation instead of attempting to determine equality of projections that may not be as normalized as possible (i.e. because of lazy norm, or just containing inference variables that prevent us from resolving an impl). Only do this when the new solver is enabled
Add ui test for implementation on projection
The error in full can be seen in https://github.com/rust-lang/rust/pull/107263 and is part of why the PR is blocked (it still requires the approval from the team for supporting it).
r? ``@oli-obk``
Add a couple random projection tests for new solver
Self-explanatory, they're just some cases that have been on my mind in the past (especially `tests/ui/traits/new-solver/param-candidate-doesnt-shadow-project.rs`).
Avoid exposing type parameters and implementation details sourced from macro expansions
Fixes#107745.
~~I would like to **request some guidance** for this issue, because I don't think this is a good fix (a band-aid at best).~~
### The Problem
The code
```rust
fn main() {
println!("{:?}", []);
}
```
gets desugared into (`rustc +nightly --edition=2018 issue-107745.rs -Z unpretty=hir`):
```rust
#[prelude_import]
use std::prelude::rust_2018::*;
#[macro_use]
extern crate std;
fn main() {
{
::std::io::_print(<#[lang = "format_arguments"]>::new_v1(&["",
"\n"], &[<#[lang = "format_argument"]>::new_debug(&[])]));
};
}
```
so the diagnostics code tries to be as specific and helpful as possible, and I think it finds that `[]` needs a type parameter and so does `new_debug`. But since `[]` doesn't have an origin for the type parameter definition, it points to `new_debug` instead and leaks the internal implementation detail since all `[]` has is an type inference variable.
### ~~The Bad Fix~~
~~This PR currently tries to fix the problem by bypassing the generated function `<#[lang = "format_argument"]>::new_debug` to avoid its generic parameter (I think it is auto-generated from the argument `[_; 0]`?) from getting collected as an `InsertableGenericArg`. This is problematic because it also prevents the help from getting displayed.~~
~~I think this fix is not ideal and hard-codes the format generated code pattern, but I can't think of a better fix. I have tried asking on Zulip but no responses there yet.~~
Fix implied outlives bounds logic for projections
The logic here is subtly wrong. I put a bit of an explanation in a767d7b5165cea8ee5cbe494a4a636c50ef67c9c.
TL;DR: we register outlives predicates to be proved, because wf code normalizes projections (from the unnormalized types) to type variables. This causes us to register those as constraints instead of implied. This was "fine", because we later added that implied bound in the normalized type, and delayed registering constraints. When I went to cleanup `free_region_relations` to *not* delay adding constraints, this bug was uncovered.
cc. `@aliemjay` because this caused your test failure in #99832 (I only realized as I was writing this)
r? `@nikomatsakis`
Implement some tweaks in the new solver
I've been testing the new solver on some small codebases, and these are a few small changes I've needed to make.
The most "controversial" here is implementing `trait_candidate_should_be_dropped_in_favor_of`, which I just implemented to always return false. This surprisingly allows some code to compile, without us having to actually decide on any semantics yet.
r? `@rust-lang/initiative-trait-system-refactor`
Terminals supporting the OSC8 Hyperlink Extension can support inline
anchors where the text is user defineable but clicking on it opens a
browser to a specified URLs, just like `<a href="URL">` does in HTML.
https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
correctly update goals in the cache
we may want to actually write the response for our goal into the provisional or global cache instead of simply using the result from the last iteration '^^
r? ```@rust-lang/initiative-trait-system-refactor```
Now that the compiler accepts "-Z instrument-xray" option only when
targeting one of the supported targets, make sure to not run the
codegen tests where the compiler will fail.
Like with other compiletests, we don't have access to internals,
so simply hardcode a list of supported architectures here.
This is somewhat important because LLVM enables the pass based on
target architecture, but support by the target OS also matters.
For example, XRay attributes are processed by codegen for macOS
targets, but Apple linker fails to process relocations in XRay
data sections, so the feature as a whole is not supported there
for the time being.
Make `derive_const` derive properly const-if-const impls
Fixes#107774Fixes#107666
Also fixes rendering of const-if-const bounds in pretty printing.
r? ```@oli-obk``` or ```@fee1-dead```
Remove astconv usage in diagnostic
Fixes#107775
Location of the test sucks, I know, but I needed to put it somewhere 😓
The issue here is that the root cause of the issue has nothing to do with what's being tested, so I couldn't really give it a better name. Oh well.
Rename `PointerSized` to `PointerLike`
The old name was unnecessarily vague. This PR renames a nightly language feature that I added, so I don't think it needs any additional approval, though anyone can feel free to speak up if you dislike the rename.
It's still unsatisfying that we don't the user which of {size, alignment} is wrong, but this trait really is just a stepping stone for a more generalized mechanism to create `dyn*`, just meant for nightly testing, so I don't think it really deserves additional diagnostic machinery for now.
Fixes#107696, cc ``@RalfJung``
r? ``@eholk``
Rollup of 8 pull requests
Successful merges:
- #100599 (Add compiler error E0523 long description and test)
- #107471 (rustdoc: do not include empty default-settings tag in HTML)
- #107555 (Modify existing bounds if they exist)
- #107662 (Turn projections into copies in CopyProp.)
- #107695 (Add test for Future inflating arg size to 3x )
- #107700 (Run the tools builder on all PRs)
- #107706 (Mark 'atomic_mut_ptr' methods const)
- #107709 (Fix problem noticed in PR106859 with char -> u8 suggestion)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Fix problem noticed in PR106859 with char -> u8 suggestion
HN reader `@ayosec` noticed that my #106859 a few weeks back, malfunctions if you have a Unicode escape, the code suggested b'\u{0}' if you tried to use '\u{0}' where a byte should be, when of course b'\u{0}' is not a byte literal, regardless of the codepoint you can't write Unicode escapes in a byte literal at all.
My proposed fix here just checks that the "character" you wrote is fewer than 5 bytes, thus allowing \x7F and similar escapes but conveniently forbidding even the smallest Unicode escape \u{0} before offering the suggestion as before.
I have provided an updated test which includes examples which do and don't work because of this additional rule.
Modify existing bounds if they exist
Fixes#107335.
This implementation is kinda gross but I don't really see a better way to do it.
This primarily does two things: Modifies `suggest_constraining_type_param` to accept a new parameter that indicates a span to be replaced instead of added, if presented, and limit the additive suggestions to either suggest a new bound on an existing bound (see newly added unit test) or add the generics argument if a generics argument wasn't found.
The former change is required to retain the capability to add an entirely new bounds if it was entirely omitted.
r? ``@compiler-errors``
Fix suggestions rendering when the diff span is multiline
Fixes#92741
cc `@estebank`
I think, I finally fixed. I still want to go back and try to clean up the code a bit. I'm open to suggestions.
Some examples of the new suggestions:
```
help: consider removing the borrow
|
2 - &
|
```
```
help: consider removing the borrow
|
2 - &
3 - mut
|
```
```
help: consider removing the borrow
|
2 - &
3 - mut if true { true } else { false }
2 + if true { true } else { false }
|
```
Should we add a test to ensure this behavior doesn't disappear in the future?
This adds one more test that should track improvements to generator
layout, like #62958 and #62575.
In particular, this test highlights suboptimal layout, as the storage
for the argument future is not being reused across its usage as `upvar`,
`local` and `awaitee` (being polled to completion).
Sort Generator `print-type-sizes` according to their yield points
Especially when trying to diagnose runaway future sizes, it might be more intuitive to sort the variants according to the control flow (aka their yield points) rather than the size of the variants.
Refine error spans for "The trait bound `T: Trait` is not satisfied" when passing literal structs/tuples
This PR adds a new heuristic which refines the error span reported for "`T: Trait` is not satisfied" errors, by "drilling down" into individual fields of structs/enums/tuples to point to the "problematic" value.
Here's a self-contained example of the difference in error span:
```rs
struct Burrito<Filling> {
filling: Filling,
}
impl <Filling: Delicious> Delicious for Burrito<Filling> {}
fn eat_delicious_food<Food: Delicious>(food: Food) {}
fn will_type_error() {
eat_delicious_food(Burrito { filling: Kale });
// ^~~~~~~~~~~~~~~~~~~~~~~~~ (before) The trait bound `Kale: Delicious` is not satisfied
// ^~~~ (after) The trait bound `Kale: Delicious` is not satisfied
}
```
(kale is fine, this is just a silly food-based example)
Before this PR, the error span is identified as the entire argument to the generic function `eat_delicious_food`. However, since only `Kale` is the "problematic" part, we can point at it specifically. In particular, the primary error message itself mentions the missing `Kale: Delicious` trait bound, so it's much clearer if this part is called out explicitly.
---
The _existing_ heuristic tries to label the right function argument in `point_at_arg_if_possible`. It goes something like this:
- Look at the broken base trait `Food: Delicious` and find which generics it mentions (in this case, only `Food`)
- Look at the parameter type definitions and find which of them mention `Filling` (in this case, only `food`)
- If there is exactly one relevant parameter, label the corresponding argument with the error span, instead of the entire call
This PR extends this heuristic by further refining the resulting expression span in the new `point_at_specific_expr_if_possible` function. For each `impl` in the (broken) chain, we apply the following strategy:
The strategy to determine this span involves connecting information about our generic `impl`
with information about our (struct) type and the (struct) literal expression:
- Find the `impl` (`impl <Filling: Delicious> Delicious for Burrito<Filling>`)
that links our obligation (`Kale: Delicious`) with the parent obligation (`Burrito<Kale>: Delicious`)
- Find the "original" predicate constraint in the impl (`Filling: Delicious`) which produced our obligation.
- Find all of the generics that are mentioned in the predicate (`Filling`).
- Examine the `Self` type in the `impl`, and see which of its type argument(s) mention any of those generics.
- Examing the definition for the `Self` type, and identify (for each of its variants) if there's a unique field
which uses those generic arguments.
- If there is a unique field mentioning the "blameable" arguments, use that field for the error span.
Before we do any of this logic, we recursively call `point_at_specific_expr_if_possible` on the parent
obligation. Hence we refine the `expr` "outwards-in" and bail at the first kind of expression/impl we don't recognize.
This function returns a `Result<&Expr, &Expr>` - either way, it returns the `Expr` whose span should be
reported as an error. If it is `Ok`, then it means it refined successfull. If it is `Err`, then it may be
only a partial success - but it cannot be refined even further.
---
I added a new test file which exercises this new behavior. A few existing tests were affected, since their error spans are now different. In one case, this leads to a different code suggestion for the autofix - although the new suggestion isn't _wrong_, it is different from what used to be.
This change doesn't create any new errors or remove any existing ones, it just adjusts the spans where they're presented.
---
Some considerations: right now, this check occurs in addition to some similar logic in `adjust_fulfillment_error_for_expr_obligation` function, which tidies up various kinds of error spans (not just trait-fulfillment error). It's possible that this new code would be better integrated into that function (or another one) - but I haven't looked into this yet.
Although this code only occurs when there's a type error, it's definitely not as efficient as possible. In particular, there are definitely some cases where it degrades to quadratic performance (e.g. for a trait `impl` with 100+ generic parameters or 100 levels deep nesting of generic types). I'm not sure if these are realistic enough to worry about optimizing yet.
There's also still a lot of repetition in some of the logic, where the behavior for different types (namely, `struct` vs `enum` variant) is _similar_ but not the same.
---
I think the biggest win here is better targeting for tuples; in particular, if you're using tuples + traits to express variadic-like functions, the compiler can't tell you which part of a tuple has the wrong type, since the span will cover the entire argument. This change allows the individual field in the tuple to be highlighted, as in this example:
```
// NEW
LL | want(Wrapper { value: (3, q) });
| ---- ^ the trait `T3` is not implemented for `Q`
// OLD
LL | want(Wrapper { value: (3, q) });
| ---- ^~~~~~~~~~~~~~~~~~~~~~~~~ the trait `T3` is not implemented for `Q`
```
Especially with large tuples, the existing error spans are not very effective at quickly narrowing down the source of the problem.
Rollup of 5 pull requests
Successful merges:
- #107553 (Suggest std::ptr::null if literal 0 is given to a raw pointer function argument)
- #107580 (Recover from lifetimes with default lifetimes in generic args)
- #107669 (rustdoc: combine duplicate rules in ayu CSS)
- #107685 (Suggest adding a return type for async functions)
- #107687 (Adapt SROA MIR opt for aggregated MIR)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Suggest std::ptr::null if literal 0 is given to a raw pointer function argument
Implementation feels a little sus (we're parsing the span for a `0`) but it seems to fall in line the string-expected-found-char condition right above this check, so I think it's fine.
Feedback appreciated on help text? I think it's consistent but it does sound a little awkward maybe?
Fixes#107517
Adds the extended error documentation for E0523 to indicate that the
error is no longer produced by the compiler.
Update the E0464 documentation to include example code that produces the
error.
Remove the error message E0523 from the compiler and replace it with an
internal compiler error.
don't point at nonexisting code beyond EOF when warning about delims
Previously we would show this:
```
warning: unnecessary braces around block return value
--> /tmp/bad.rs:1:8
|
1 | fn a(){{{
| ^ ^
|
= note: `#[warn(unused_braces)]` on by default
help: remove these braces
|
1 - fn a(){{{
1 + fn a(){{
|
```
which is now hidden in this case.
We would create a span spanning between the pair of redundant {}s but there is only EOF instead of the `}` so we would previously point at nothing. This would cause the debug assertion ice to trigger. I would have loved to just only point at the second delim and say "you can remove that" but I'm not sure how to do that without refactoring the entire diagnostic which seems tricky. :( But given that this does not seem to regress any other tests we have, I think this edge-casey enough be acceptable.
Fixes https://github.com/rust-lang/rust/issues/107423
r? `@compiler-errors`
Especially when trying to diagnose runaway future sizes, it might be
more intuitive to sort the variants according to the control flow
(aka their yield points) rather than the size of the variants.
Previously we would show this:
```
warning: unnecessary braces around block return value
--> /tmp/bad.rs:1:8
|
1 | fn a(){{{
| ^ ^
|
= note: `#[warn(unused_braces)]` on by default
help: remove these braces
|
1 - fn a(){{{
1 + fn a(){{
|
```
which is now hidden in this case.
We would create a span spanning between the pair of redundant {}s but there is only EOF instead of the `}` so we would previously point at nothing.
This would cause the debug assertion ice to trigger.
I would have loved to just only point at the second delim and say "you can remove that" but I'm not sure how to do that without refactoring the entire diagnostic which seems tricky. :(
But given that this does not seem to regress any other tests we have, I think this edge-casey enough be acceptable.
Fixes https://github.com/rust-lang/rust/issues/107423
r? @compiler-errors
Fix suggestion for coercing Option<&String> to Option<&str>
Fixes#107604
This also makes the diagnostic `MachineApplicable`, and runs `rustfix` to check we're not producing incorrect code.
``@rustbot`` label +A-diagnostics
Don't cause a cycle when formatting query description that references a FnDef
When a function returns `-> _`, we use typeck to compute what the resulting type of the body _should_ be. If we call another query inside of typeck and hit a cycle error, we attempt to report the cycle error which requires us to compute all of the query descriptions for the stack.
However, if one of the queries in that cycle has a query description that references this function as a FnDef type, we'll cause a *second* cycle error from within the cycle error reporting code, since rendering a FnDef requires us to compute its signature. This causes an unwrap to ICE, since during the *second* cycle reporting code, we try to look for a job that isn't in the active jobs list.
We can avoid this by using `with_no_queries!` when computing these query descriptions.
Fixes#107089
The only drawback is that the rendering of opaque types in cycles regresses a bit :| I'm open to alternate suggestions about how we may handle this...
Emit warnings on unused parens in index expressions
Fixes: #96606.
I am not sure what the best term for "index expression" is. Is there a better term we could use?
Don't generate unecessary `&&self.field` in deriving Debug
Since unsized fields may only be the last one in a struct, we only need to generate a double reference (`&&self.field`) for the final one.
cc `@nnethercote`
Suggest `{var:?}` when finding `{?:var}` in inline format strings
Link to issue: https://github.com/rust-lang/rust/issues/106572
This is my first PR to this project, so hopefully I can get some good pointers with me from the first PR.
Currently my idea was to test out whether or not this is the correct solution to this issue and then hopefully expand upon the idea to not only work for Debug formatting but for all of them. If this is a valid solution, I will create a new issue to give a better error message to a broader range of wrong-order formatting.
Erase regions before doing uninhabited check in borrowck
~Also, fingerprint query keys/values when debug assertions are enabled. This should make it easier to check for issues like this without `-Cincremental`, and make UI tests a bit cleaner.~ edit: moving that to a separate PR
Fixes#107505
Improve diagnostic for missing space in range pattern
Improves the diagnostic in #107425 by turning it into a note explaining the parsing issue.
r? `@compiler-errors`
Revert "Teach parser to understand fake anonymous enum syntax" and related commits
anonymous enum types are currently ambiguous in positions like:
* `|` operator: `a as fn() -> B | C`
* closure args: `|_: as fn() -> A | B`
I first tried to thread around `RecoverAnonEnum` into all these positions, but the resulting complexity in the compiler is IMO not worth it, or at least worth a bit more thinking time. In the mean time, let's revert this syntax for now, so we can go back to the drawing board.
Fixes#107461
cc: `@estebank` `@cjgillot` #106960
---
### Squashed revert commits:
Revert "review comment: Remove AST AnonTy"
This reverts commit 020cca8d36.
Revert "Ensure macros are not affected"
This reverts commit 12d18e4031.
Revert "Emit fewer errors on patterns with possible type ascription"
This reverts commit c847a01a3b.
Revert "Teach parser to understand fake anonymous enum syntax"
This reverts commit 2d82420665.
Revert "review comment: Remove AST AnonTy"
This reverts commit 020cca8d36.
Revert "Ensure macros are not affected"
This reverts commit 12d18e4031.
Revert "Emit fewer errors on patterns with possible type ascription"
This reverts commit c847a01a3b.
Revert "Teach parser to understand fake anonymous enum syntax"
This reverts commit 2d82420665.
Add proc-macro boilerplate to crt-static test
I was seeing this failure when running ui tests with with a `-Cpanic=abort` stdlib targeting fuchsia:
```
---- [ui] tests/ui/proc-macro/crt-static.rs stdout ----
normalized stderr:
warning: building proc macro crate with `panic=abort` may crash the compiler should the proc-macro panic
warning: 1 warning emitted
The actual stderr differed from the expected stderr.
```
`force-host` was enough to stop it from running/failing, not sure if I should also add `needs-unwind`?
Fix syntax in `-Zunpretty-expanded` output for derived `PartialEq`.
If you do `derive(PartialEq)` on a packed struct, the output shown by `-Zunpretty=expanded` includes expressions like this:
```
{ self.x } == { other.x }
```
This is invalid syntax. This doesn't break compilation, because the AST nodes are constructed within the compiler. But it does mean anyone using `-Zunpretty=expanded` output as a guide for hand-written impls could get a nasty surprise.
This commit fixes things by instead using this form:
```
({ self.x }) == ({ other.x })
```
r? ``@RalfJung``
Remove confusing 'while checking' note from opaque future type mismatches
Maybe I'm just misinterpreting the wording of the note. The only value I can see in this note is that it points out where the async's opaque future is coming from, but the way it's doing it is misleading IMO.
For example:
```rust
note: while checking the return type of the `async fn`
--> $DIR/dont-suggest-missing-await.rs:7:24
|
LL | async fn make_u32() -> u32 {
| ^^^ checked the `Output` of this `async fn`, found opaque type
```
We point at the type `u32` in the HIR, but then say "found opaque type". We also say "while checking"... but we're typechecking a totally different function when we get this type mismatch!
r? ``@estebank`` but feel free to reassign and/or take your time reviewing this. I'd be inclined to also discuss reworking the presentation of this type mismatch to restore some of these labels in a way that makes it more clear what it's trying to point out.
The check previously matched this, and suggested adding a missing
`struct`:
pub Foo(...):
It was probably intended to match this instead (semicolon instead of
colon):
pub Foo(...);
Strengthen validation of FFI attributes
Previously, `codegen_attrs` validated the attributes `#[ffi_pure]`, `#[ffi_const]`, and `#[ffi_returns_twice]` to make sure that they were only used on foreign functions. However, this validation was insufficient in two ways:
1. `codegen_attrs` only sees items for which code must be generated, so it was unable to raise errors when the attribute was incorrectly applied to macros and the like.
2. the validation code only checked that the item with the attr was foreign, but not that it was a foreign function, allowing these attributes to be applied to foreign statics as well.
This PR moves the validation to `check_attr`, which sees all items. It additionally changes the validation to ensure that the attribute's target is `Target::ForeignFunction`, only allowing the attributes on foreign functions and not foreign statics. Because these attributes are unstable, there is no risk for backwards compatibility. The changes also ending up making the code much easier to read.
This PR is best reviewed commit by commit. Additionally, I was considering moving the tests to the `attribute` subdirectory, to get them out of the general UI directory. I could do that as part of this PR or a follow-up, as the reviewer prefers.
CC: #58328, #58329
Do not depend on Generator trait when deducing closure signature
1. Do not depend on `Generator` trait when deducing closure signature.
2. Compare the name of the `Generator::Return` associated item, rather than its order in the trait. Seems more stable this way.
Fixing confusion between mod and remainder
Like many programming languages, rust too confuses remainder and modulus. The `%` operator and the associated `Rem` trait is (as the trait name suggests) the remainder, but since most people are linguistically more familiar with the modulus the documentation sometimes claims otherwise. This PR tries to fix this problem in rustc.
If you do `derive(PartialEq)` on a packed struct, the output shown by
`-Zunpretty=expanded` includes expressions like this:
```
{ self.x } == { other.x }
```
This is invalid syntax. This doesn't break compilation, because the AST
nodes are constructed within the compiler. But it does mean anyone using
`-Zunpretty=expanded` output as a guide for hand-written impls could get
a nasty surprise.
This commit fixes things by instead using this form:
```
({ self.x }) == ({ other.x })
```
Modify primary span label for E0308
Looking at the reactions to https://hachyderm.io/`@ekuber/109622160673605438,` a lot of people seem to have trouble understanding the current output, where the primary span label on type errors talks about the specific types that diverged, but these can be deeply nested type parameters. Because of that we could see "expected i32, found u32" in the label while the note said "expected Vec<i32>, found Vec<u32>". This understandably confuses people. I believe that once people learn to read these errors it starts to make more sense, but this PR changes the output to be more in line with what people might expect, without sacrificing terseness.
Fix#68220.
Use `ObligationCtxt::new_in_snapshot` in `satisfied_from_param_env`
We can evaluate nested `ConstEvaluatable` obligations in an evaluation probe, which will ICE if we use `ObligationCtxt::new`.
Fixes#107474Fixes#106666
r? `@BoxyUwU` but feel free to reassign
cc `@JulianKnodt` who i think added this assertion code
Not sure if the rustdoc test is needed, but can't hurt. They're the same root cause, though.
Implement unsizing in the new trait solver
This makes hello world compile! Ignore the first commit, that's just #107146 which is waiting on merge.
I'll leave some comments inline about design choices that might be debatable.
r? `@lcnr` (until we have a new trait solver reviewer group...)
Fix invalid float literal suggestions when recovering an integer
Only suggest adding a zero to integers with a preceding dot when the change will result in a valid floating point literal.
For example, `.0x0` should not be turned into `0.0x0`.
r? nnethercote
Only suggest adding a zero to integers with a preceding dot when the change will
result in a valid floating point literal.
For example, `.0x0` should not be turned into `0.0x0`.
The original tweet in the chain linked to, and thus the through line of links back to Anna's tweet where she named the turbofish (https://web.archive.org/web/20210911061514/https://twitter.com/whoisaldeka/status/914914008225816576) are lost as the user whoisaldeka has deleted their twitter account.
Switching to an archive link preserves this through line, allowing someone to browse back to see the point at which Anna created the turbofish, as was the original intent of including this context.
Don't re-export private/unstable ArgumentV1 from `alloc`.
The `alloc::fmt::ArgumentV1` re-export was marked as `#[stable]` even though the original `core::fmt::ArgumentV1` is `#[unstable]` (and `#[doc(hidden)]`).
(It wasn't usable though:
```
error[E0658]: use of unstable library feature 'fmt_internals': internal to format_args!
--> src/main.rs:4:12
|
4 | let _: alloc::fmt::ArgumentV1 = todo!();
| ^^^^^^^^^^^^^^^^^^^^^^
|
= help: add `#![feature(fmt_internals)]` to the crate attributes to enable
```
)
Part of #99012
Currently, deriving on packed structs has some non-trivial limitations,
related to the fact that taking references on unaligned fields is UB.
The current approach to field accesses in derived code:
- Normal case: `&self.0`
- In a packed struct that derives `Copy`: `&{self.0}`
- In a packed struct that doesn't derive `Copy`: `&self.0`
Plus, we disallow deriving any builtin traits other than `Default` for any
packed generic type, because it's possible that there might be
misaligned fields. This is a fairly broad restriction.
Plus, we disallow deriving any builtin traits other than `Default` for most
packed types that don't derive `Copy`. (The exceptions are those where the
alignments inherently satisfy the packing, e.g. in a type with
`repr(packed(N))` where all the fields have alignments of `N` or less
anyway. Such types are pretty strange, because the `packed` attribute is
not having any effect.)
This commit introduces a new, simpler approach to field accesses:
- Normal case: `&self.0`
- In a packed struct: `&{self.0}`
In the latter case, this requires that all fields impl `Copy`, which is
a new restriction. This means that the following example compiles under
the old approach and doesn't compile under the new approach.
```
#[derive(Debug)]
struct NonCopy(u8);
#[derive(Debug)
#[repr(packed)]
struct MyType(NonCopy);
```
(Note that the old approach's support for cases like this was brittle.
Changing the `u8` to a `u16` would be enough to stop it working. So not
much capability is lost here.)
However, the other constraints from the old rules are removed. We can now
derive builtin traits for packed generic structs like this:
```
trait Trait { type A; }
#[derive(Hash)]
#[repr(packed)]
pub struct Foo<T: Trait>(T, T::A);
```
To allow this, we add a `T: Copy` bound in the derived impl and a `T::A:
Copy` bound in where clauses. So `T` and `T::A` must impl `Copy`.
We can now also derive builtin traits for packed structs that don't derive
`Copy`, so long as the fields impl `Copy`:
```
#[derive(Hash)]
#[repr(packed)]
pub struct Foo(u32);
```
This includes types that hand-impl `Copy` rather than deriving it, such as the
following, that show up in winapi-0.2:
```
#[derive(Clone)]
#[repr(packed)]
struct MyType(i32);
impl Copy for MyType {}
```
The new approach is simpler to understand and implement, and it avoids
the need for the `unsafe_derive_on_repr_packed` check.
One exception is required for backwards-compatibility: we allow `[u8]`
fields for now. There is a new lint for this,
`byte_slice_in_packed_struct_with_derive`.
Output tree representation on thir-tree
The current output of `-Zunpretty=thir-tree` is really cumbersome to work with, using an actual tree representation should make it easier to see what the thir looks like.
Insert whitespace to avoid ident concatenation in suggestion
This PR tweaks the suggestion of removing misplaced parentheses around trait bounds so as to avoid concatenating two identifiers. Although subtle, this should make outputs less surprising especially when applying the `MachineApplicable` suggestions automatically.
Skip possible where_clause_object_safety lints when checking `multiple_supertrait_upcastable`
Fix#106247
To achieve this, I lifted the `WhereClauseReferencesSelf` out from `object_safety_violations` and move it into `is_object_safe` (which is changed to a new query).
cc `@dtolnay`
r? `@compiler-errors`
Rollup of 8 pull requests
Successful merges:
- #106618 (Disable `linux_ext` in wasm32 and fortanix rustdoc builds.)
- #107097 (Fix def-use dominance check)
- #107154 (library/std/sys_common: Define MIN_ALIGN for m68k-unknown-linux-gnu)
- #107397 (Gracefully exit if --keep-stage flag is used on a clean source tree)
- #107401 (remove the usize field from CandidateSource::AliasBound)
- #107413 (make more pleasant to read)
- #107422 (Also erase substs for new infcx in pin move error)
- #107425 (Check for missing space between fat arrow and range pattern)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Check for missing space between fat arrow and range pattern
Fixes#107420
Ideally we wouldn't emit an error about expecting `=>` etc., but I'm not sure how to recover from this.
`@rustbot` label +A-diagnostics
Also erase substs for new infcx in pin move error
The code originally correctly erased the regions of the type it passed to the newly created infcx. But after the `fn_sig` query was made to return an `EarlyBinder<T>`, some substs that were around were substituted there without erasing their regions. They were then passed into the newly cerated infcx, which caused the ICE.
Fixes#107419
r? compiler-errors who reviewed the original PR adding this diagnostic
Fix def-use dominance check
A definition does not dominate a use in the same statement. For example
in MIR generated for compound assignment x += a (when overflow checks
are disabled).
Use stable metric for const eval limit instead of current terminator-based logic
This patch adds a `MirPass` that inserts a new MIR instruction `ConstEvalCounter` to any loops and function calls in the CFG. This instruction is used during Const Eval to count against the `const_eval_limit`, and emit the `StepLimitReached` error, replacing the current logic which uses Terminators only.
The new method of counting loops and function calls should be more stable across compiler versions (i.e., not cause crates that compiled successfully before, to no longer compile when changes to the MIR generation/optimization are made).
Also see: #103877
Special-case deriving `PartialOrd` for enums with dataless variants
I was able to get slightly better codegen by flipping the derived `PartialOrd` logic for two-variant enums. I also tried to document the implementation of the derive macro to make the special-case logic a little clearer.
```rs
#[derive(PartialEq, PartialOrd)]
pub enum A<T> {
A,
B(T)
}
```
```diff
impl<T: ::core::cmp::PartialOrd> ::core::cmp::PartialOrd for A<T> {
#[inline]
fn partial_cmp(
&self,
other: &A<T>,
) -> ::core::option::Option<::core::cmp::Ordering> {
let __self_tag = ::core::intrinsics::discriminant_value(self);
let __arg1_tag = ::core::intrinsics::discriminant_value(other);
- match ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag) {
- ::core::option::Option::Some(::core::cmp::Ordering::Equal) => {
- match (self, other) {
- (A::B(__self_0), A::B(__arg1_0)) => {
- ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0)
- }
- _ => ::core::option::Option::Some(::core::cmp::Ordering::Equal),
- }
+ match (self, other) {
+ (A::B(__self_0), A::B(__arg1_0)) => {
+ ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0)
}
- cmp => cmp,
+ _ => ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag),
}
}
}
```
Godbolt: [Current](https://godbolt.org/z/GYjEzG1T8), [New](https://godbolt.org/z/GoK78qx15)
I'm not sure how common a case comparing two enums like this (such as `Option`) is, and if it's worth the slowdown of adding a special case to the derive. If it causes overall regressions it might be worth just manually implementing this for `Option`.
The code originally correctly erased the regions of the type it passed
to the newly created infcx. But after the `fn_sig` query was made to
return an `EarlyBinder<T>`, some substs that were around were
substituted there without erasing their regions. They were then passed
into the newly cerated infcx, which caused the ICE.
Improve unexpected close and mismatch delimiter hint in TokenTreesReader
Fixes#103882Fixes#68987Fixes#69259
The inner indentation mismatching will be covered by outer block, the new added function `report_error_prone_delim_block` will find out the error prone candidates for reporting.
Remove overlapping parts of multipart suggestions
This PR adds a debug assertion that the parts of a single substitution cannot overlap, fixes a overlapping substitution from the testsuite, and fixes https://github.com/rust-lang/rust/issues/106870.
Note that a single suggestion can still have multiple overlapping substitutions / possible edits, we just don't suggest overlapping replacements in a single edit anymore.
I've also included a fix for an unrelated bug where rustfix for `explicit_outlives_requirements` would produce multiple trailing commas for a where clause.
internally change regions to be covariant
Surprisingly, we consider the reference type `&'a T` to be contravaraint in its lifetime parameter. This is confusing and conflicts with the documentation we have in the reference, rustnomicon, and rustc-dev-guide. This also arguably not the correct use of terminology since we can use `&'static u8` in a place where `&' a u8` is expected, this implies that `&'static u8 <: &' a u8` and consequently `'static <: ' a`, hence covariance.
Because of this, when relating two types, we used to switch the argument positions in a confusing way:
`Subtype(&'a u8 <: &'b u8) => Subtype('b <: 'a) => Outlives('a: 'b) => RegionSubRegion('b <= 'a)`
The reason for the current behavior is probably that we wanted `Subtype('b <: 'a)` and `RegionSubRegion('b <= 'a)` to be equivalent, but I don' t think this is a good reason since these relations are sufficiently different in that the first is a relation in the subtyping lattice and is intrinsic to the type-systems, while the the second relation is an implementation detail of regionck.
This PR changes this behavior to use covariance, so..
`Subtype(&'a u8 <: &'b u8) => Subtype('a <: 'b) => Outlives('a: 'b) => RegionSubRegion('b <= 'a) `
Resolves#103676
r? `@lcnr`