The illumos linker does not support --strip-debug
When building and testing rust 1.64.0 on illumos, we saw a large number of failing tests associated with:
```
= note: ld: fatal: unrecognized option '--strip-debug'
ld: fatal: use the -z help option for usage information
collect2: error: ld returned 1 exit status
```
The illumos linker does not support the `--strip-debug` option (although it does support `--strip-all`).
Make diagnostic for unsatisfied `Termination` bounds more precise
Don't blindly emit a diagnostic claiming that “*`main` has an invalid return type*” if we encounter a type that should but doesn't implement `std::process::Termination` and isn't actually the return type of the program entry `main`.
Fixes#103052.
``@rustbot`` label A-diagnostics T-compiler T-libs
r? diagnostics
PR #98758 introduced code to avoid redundant assertions in derived code
like this:
```
let _: ::core::clone::AssertParamIsClone<u32>;
let _: ::core::clone::AssertParamIsClone<u32>;
```
But the predicate `is_simple_path` introduced as part of this failed to
account for generic arguments. Therefore the deriving code erroneously
considers types like `Option<bool>` and `Option<f32>` to be the same.
This commit fixes `is_simple_path`.
Fixes#103157.
Remove "execute" bit from lock file permissions
Previously, flock would set the "execute" bit on Rust lock files. That makes no sense.
This patch clears the "execute" bit on Rust lock files.
See issue #102531.
Rollup of 4 pull requests
Successful merges:
- #102454 (Suggest parentheses for possible range method calling)
- #102466 (only allow `ConstEquate` with `feature(gce)`)
- #102945 (Do not register placeholder `RegionOutlives` obligations when `considering_regions` is false)
- #103091 (rustdoc: remove unused HTML class `sidebar-title`)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Do not register placeholder `RegionOutlives` obligations when `considering_regions` is false
**NOTE:** I'm kinda just putting this up for discussion. I'm not certain this is correct...?
This was introduced in [`608625d`](608625dae9 (diff-6e54b18681342ec725d75591dbf384ad08cd73df29db00485fe51b4e90f76ff7R361)).
Interestingly, we only check `data.has_placeholders()` for `RegionOutlives`, and not for `TypeOutlives`... why? For the record, that different treatment between `RegionOutlives` and `TypeOutlives` is why the fix "The compiling succeeds when all `'a : 'b` are replaced with `&'a () : 'b`" in #100689 _"works"_, but it seems like an implementation detail considering this.
Also, why do we care about placeholder regions being registered if `considering_regions` is false? It doesn't seem to affect any UI tests, for example.
r? `@lcnr`
Fixes#102899Fixes#100689
Sometimes it is convenient to return a subdiagnostic enum where one or
more of the variants don't add anything to the diagnostic.
Signed-off-by: David Wood <david.wood@huawei.com>
Documentation comments shouldn't affect the diagnostic derive in any
way, but explicit support has to be added for ignoring the `doc`
attribute.
Signed-off-by: David Wood <david.wood@huawei.com>
Rollup of 5 pull requests
Successful merges:
- #103087 (Documentation BTreeMap::append's behavior for already existing keys)
- #103089 (Mark derived StructuralEq as automatically derived.)
- #103102 (Clarify the possible return values of `len_utf16`)
- #103109 (PhantomData: inline a macro that is used only once)
- #103120 (rustdoc: Do not expect `doc(primitive)` modules to always exist)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Fix subst issues with return-position `impl Trait` in trait
1. Fix an issue where we were rebase impl substs onto trait method substs, instead of trait substs
2. Fix an issue where early-bound regions aren't being mapped correctly for RPITIT hidden types
Fixes#102301Fixes#102310Fixes#102334Fixes#102918
Fix missing explanation of where the borrowed reference is used when the same borrow occurs multiple times due to loop iterations
Fix#99824.
Problem of the issue:
If a borrow occurs in a loop, the borrowed reference could be invalidated at the same place at next iteration of the loop. When this happens, the point where the borrow occurs is the same as the intervening point that might invalidate the reference in the loop. This causes a problem for the current code finding the point where the resulting reference is used, so that the explanation of the cause will be missing. As the second point of "explain all errors in terms of three points" (see [leveraging intuition framing errors in terms of points"](https://rust-lang.github.io/rfcs/2094-nll.html#leveraging-intuition-framing-errors-in-terms-of-points), this explanation is very helpful for user to understand the error.
In the current implementation, the searching region for finding the location where the borrowed reference is used is limited to between the place where the borrow occurs and the place where the reference is invalidated. If those two places happen to be the same, which indicates that the borrow and invalidation occur at the same place in a loop, the search will fail.
One solution to the problem is when these two places are the same, find the terminator of the loop, and then use the location of the loop terminator instead of the location of the borrow for the region to find the place where the borrowed reference is used.
pretty: fix to print some lifetimes on HIR pretty-print
HIR pretty-printer doesn't seem to print some lifetimes in types. This PR fixes that.
Closes https://github.com/rust-lang/rust/issues/85089
Get rid of `rustc_query_description!`
**I am not entirely sure whether this is an improvement and would like to get your feedback on it.**
Helps with #96524.
Queries can provide an arbitrary expression for their description and their caching behavior. Before, these expressions where stored in a `rustc_query_description` macro emitted by the `rustc_queries` macro, and then used in `rustc_query_impl` to fill out the methods for the `QueryDescription` trait.
Instead, we now emit two new modules from `rustc_queries` containing the functions with the expressions. `rustc_query_impl` calls these functions now instead of invoking the macro.
Since we are now defining some of the functions in `rustc_middle::query`, we now need all the imports for the key types mthere as well.
r? `@cjgillot`
Rollup of 6 pull requests
Successful merges:
- #102773 (Use semaphores for thread parking on Apple platforms)
- #102884 (resolve: Some cleanup, asserts and tests for lifetime ribs)
- #102954 (Add missing checks for `doc(cfg_hide(...))`)
- #102998 (Drop temporaries created in a condition, even if it's a let chain)
- #103003 (Fix `suggest_floating_point_literal` ICE)
- #103041 (Update cargo)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Drop temporaries created in a condition, even if it's a let chain
Fixes#100513.
During the lowering from AST to HIR we wrap expressions acting as conditions in a `DropTemps` expression so that any temporaries created in the condition are dropped after the condition is executed. Effectively this means we transform
```rust
if Some(1).is_some() { .. }
```
into (roughly)
```rust
if { let _t = Some(1).is_some(); _t } { .. }
```
so that if we create any temporaries, they're lifted into the new scope surrounding the condition, so for example something along the lines of
```rust
if { let temp = Some(1); let _t = temp.is_some(); _t }.
```
Before this PR, if the condition contained any let expressions we would not introduce that new scope, instead leaving the condition alone. This meant that in a let-chain like
```rust
if get_drop("first").is_some() && let None = get_drop("last") {
println!("second");
} else { .. }
```
the temporary created for `get_drop("first")` would be lifted into the _surrounding block_, which caused it to be dropped after the execution of the entire `if` expression.
After this PR, we wrap everything but the `let` expression in terminating scopes. The upside to this solution is that it's minimally invasive, but the downside is that in the worst case, an expression with `let` exprs interspersed like
```rust
if get_drop("first").is_some()
&& let Some(_a) = get_drop("fifth")
&& get_drop("second").is_some()
&& let Some(_b) = get_drop("fourth") { .. }
```
gets _multiple_ new scopes, roughly
```rust
if { let _t = get_drop("first").is_some(); _t }
&& let Some(_a) = get_drop("fifth")
&& { let _t = get_drop("second").is_some(); _t }
&& let Some(_b) = get_drop("fourth") { .. }
```
so instead of all of the temporaries being dropped at the end of the entire condition, they will be dropped right after they're evaluated (before the subsequent `let` expr). So while I'd say the drop behavior around let-chains is _less_ surprising after this PR, it still might not exactly match what people might expect.
For tests, I've just extended the drop order tests added in #100526. I'm not sure if that's the best way to go about it, though, so suggestions are welcome.
Add missing checks for `doc(cfg_hide(...))`
Part of #43781.
The `doc(cfg_hide(...))` attribute can only be used at the crate level and takes a list of attributes as argument.
r? ```@Manishearth```
Make `dyn*` casts into a coercion, allow `dyn*` upcasting
I know that `dyn*` is likely not going to be a feature exposed to surface Rust, but this makes it slightly more ergonomic to write tests for these types anyways. ... and this was just fun to implement anyways.
1. Make `dyn*` into a coercion instead of a cast
2. Enable `dyn*` upcasting since we basically get it for free
3. Simplify some of the cast checking code since we're using the coercion path now
r? `@eholk` but feel free to reassign
cc `@nikomatsakis` and `@tmandry` who might care about making `dyn*` casts into a coercion
Correctly handle path stability for 'use tree' items
PR #95956 started checking the stability of path segments.
However, this was not applied to 'use tree' items
(e.g. 'use some::path::{ItemOne, ItemTwo}') due to the way
that we desugar these items in HIR lowering.
This PR modifies 'use tree' lowering to preserve resolution
information, which is needed by stability checking.
Queries can provide an arbitrary expression for their description and
their caching behavior. Before, these expressions where stored in a
`rustc_query_description` macro emitted by the `rustc_queries` macro,
and then used in `rustc_query_impl` to fill out the methods for the
`QueryDescription` trait.
Instead, we now emit two new modules from `rustc_queries` containing the
functions with the expressions. `rustc_query_impl` calls these functions
now instead of invoking the macro.
Since we are now defining some of the functions in
`rustc_middle::query`, we now need all the imports for the key types
there as well.
Detect and reject out-of-range integers in format string literals
Until now out-of-range integers in format string literals were silently ignored. They wrapped around to zero at usize::MAX, producing unexpected results.
When using debug builds of rustc, such integers in format string literals even cause an 'attempt to add with overflow' panic in rustc.
Fix this by producing an error diagnostic for integers in format string literals which do not fit into usize.
Fixes#102528
Suppress irrefutable let patterns lint for prefixes in match guards
In match guards, irrefutable prefixes might use the bindings created by the match pattern. Ideally, we check for this, but we can do the next best thing and just not lint for irrefutable prefixes in match guards.
Fixes#98361
More dupe word typos
I only picked those changes (from the regex search) that I am pretty certain doesn't change meaning and is just a typo fix. Do correct me if any fix is undesirable and I can revert those. Thanks.
Move `IntoDiagnostic` conformance for `TargetDataLayoutErrors` into `rustc_errors`
Addressed this suggestion https://github.com/rust-lang/rust/pull/101558#issuecomment-1243830009.
This way we comply with the Coherence rule given that `IntoDiagnostic` trait is defined in `rustc_errors`, and almost all other crates depend on it.
In match guards, irrefutable prefixes might use the bindings created
by the match pattern. Ideally, we check for this, but we can do the
next best thing and just not lint for irrefutable prefixes in match
guards.
replace ReErased with fresh region vars in opaque types
See inline comments.
Prior art #102943. cc ``@compiler-errors`` ``@oli-obk``
Fixes#100267Fixes#101940Fixes#102649Fixes#102510
Add suggestion to the "missing native library" error
If we fail to locate a native library that we are linking with, it could be the case the user entered a complete file name like `foo.lib` or `libfoo.a` when we expect them to simply provide `foo`.
In this situation, we now detect that case and suggest the user only provide the library name itself.
Sort elaborated existential predicates in `object_ty_for_trait`
r? `@cjgillot`
I think that #102845 caused #102933. Depending on the order that we elaborate these existential projection predicates, there's no guarantee that they'll be sorted by def id, which is what is failing the assertion in the issue.
Fixes#102933Fixes#102973
If we fail to locate a native library that we are linking with, it could
be the case the user entered a complete file name like `foo.lib` or
`libfoo.a` when we expect them to simply provide `foo`.
In this situation, we now detect that case and suggest the user only
provide the library name itself.
Support casting boxes to dyn*
Boxes have a pointer type at codegen time which LLVM does not allow to be transparently converted to an integer. Work around this by inserting a `ptrtoint` instruction if the argument is a pointer.
r? ``@compiler-errors``
Fixes#102427
Support default-body trait functions with return-position `impl Trait` in traits
Introduce a new `Trait` candidate kind for the `ImplTraitInTrait` projection candidate, which just projects an RPITIT down to its opaque type form.
This is a hack until we lower RPITITs to regular associated types, after which we will need to rework how these default bodies are type-checked, so comments are left in a few places for us to clean up later.
Fixes#101665
Fix `let` keyword removal suggestion in structs
(1.) Fixes a bug where, given this code:
```rust
struct Foo {
let x: i32,
}
```
We were parsing the field name as `let` instead of `x`, which causes issues later on in the type-checking phase.
(2.) Also, suggestions for `let: i32` as a field regressed, displaying this extra `help:` which is removed by this PR
```
help: remove the let, the `let` keyword is not allowed in struct field definitions
|
2 - let: i32,
2 + : i32,
```
(3.) Makes the suggestion text a bit more succinct, since we don't need to re-explain that `let` is not allowed in this position (since it's in a note that follows). This causes the suggestion to render inline as well.
cc `@gimbles,` this addresses a few nits I mentioned in your PR.
Unify `tcx.constness` query and param env constness checks
The checks that we do in the `constness` query seem inconsistent with the checks that we do to determine if an item's param-env is const, so I merged them into the `constness` query and call that from the `param_env` query.
I'm not sure if this totally makes sense -- is there a case where `tcx.param_env()` would return a const param-env for an item whose `tcx.constness()` is `Constness::NotConst`? Because if not, it seems a bit dangerous that these two differ.
Luckily, not many places actually use `tcx.constness()`, and the checks in `tcx.param_env()` seem stricter than the checks in `tcx.constness()` (at least for the types of items we type-check).
Also, due to the way that `tcx.param_env()` is implemented, it _never_ used to return a const param-env for a item coming from a different crate, which also seems dangerous (though also probably not weaponizable currently, because we seldom actually compute the param-env for a non-local item).
Enforce alphabetical sorting with tidy
We have many places where things are supposed to be sorted alphabetically. For the smaller and more recent size assertions, this is mostly upheld, but in other more... alive places it's very messy.
This introduces a new tidy directive to check that a section of code is sorted alphabetically and fixes all places where sorting has gone wrong.
translation: eager translation
Part of #100717. See [Zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/336883-i18n/topic/.23100717.20lists!/near/295010720) for additional context.
- **Store diagnostic arguments in a `HashMap`**: Eager translation will enable subdiagnostics to be translated multiple times with different arguments - this requires the ability to replace the value of one argument with a new value, which is better suited to a `HashMap` than the previous storage, a `Vec`.
- **Add `AddToDiagnostic::add_to_diagnostic_with`**: `AddToDiagnostic::add_to_diagnostic_with` is similar to the previous `AddToDiagnostic::add_to_diagnostic` but takes a function that can be used by the caller to modify diagnostic messages originating from the subdiagnostic (such as performing translation eagerly). `add_to_diagnostic` now just calls `add_to_diagnostic_with` with an empty closure.
- **Add `DiagnosticMessage::Eager`**: Add variant of `DiagnosticMessage` for eagerly translated messages
(messages in the target language which don't need translated by the emitter during emission). Also adds `eager_subdiagnostic` function which is intended to be invoked by the diagnostic derive for subdiagnostic fields which are marked as needing eager translation.
- **Support `#[subdiagnostic(eager)]`**: Add support for `eager` argument to the `subdiagnostic` attribute which generates a call to `eager_subdiagnostic`.
- **Finish migrating `rustc_query_system`**: Using eager translation, migrate the remaining repeated cycle stack diagnostic.
- **Split formatting initialization and use in diagnostic derives**: Diagnostic derives have previously had to take special care when ordering the generated code so that fields were not used after a move.
This is unlikely for most fields because a field is either annotated with a subdiagnostic attribute and is thus likely a `Span` and copiable, or is a argument, in which case it is only used once by `set_arg`
anyway.
However, format strings for code in suggestions can result in fields being used after being moved if not ordered carefully. As a result, the derive currently puts `set_arg` calls last (just before emission), such as:
let diag = { /* create diagnostic */ };
diag.span_suggestion_with_style(
span,
fluent::crate::slug,
format!("{}", __binding_0),
Applicability::Unknown,
SuggestionStyle::ShowAlways
);
/* + other subdiagnostic additions */
diag.set_arg("foo", __binding_0);
/* + other `set_arg` calls */
diag.emit();
For eager translation, this doesn't work, as the message being translated eagerly can assume that all arguments are available - so arguments _must_ be set first.
Format strings for suggestion code are now separated into two parts - an initialization line that performs the formatting into a variable, and a usage in the subdiagnostic addition.
By separating these parts, the initialization can happen before arguments are set, preserving the desired order so that code compiles, while still enabling arguments to be set before subdiagnostics are added.
let diag = { /* create diagnostic */ };
let __code_0 = format!("{}", __binding_0);
/* + other formatting */
diag.set_arg("foo", __binding_0);
/* + other `set_arg` calls */
diag.span_suggestion_with_style(
span,
fluent::crate::slug,
__code_0,
Applicability::Unknown,
SuggestionStyle::ShowAlways
);
/* + other subdiagnostic additions */
diag.emit();
- **Remove field ordering logic in diagnostic derive:** Following the approach taken in earlier commits to separate formatting initialization from use in the subdiagnostic derive, simplify the diagnostic derive by removing the field-ordering logic that previously solved this problem.
r? ```@compiler-errors```
nicer errors from assert_unsafe_precondition
This makes the errors shown by cargo-careful nicer, and since `panic_no_unwind` is `nounwind noreturn` it hopefully doesn't have bad codegen impact. Thanks to `@bjorn3` for the hint!
Would be nice if we could somehow supply our own (static) message to print, currently it always prints `panic in a function that cannot unwind`. But still, this is better than before.
unify `IsPattern` and `IsImport` enum in `show_candidates`
Follow-up of #102876
A binding cannot appear in both pattern and import at the same time, so it makes sense to unify them
r? `@compiler-errors`
Check representability in adt_sized_constraint
Now that representability is a query, we can use it to preemptively avoid a cycle in `adt_sized_constraint`.
I moved the representability check into `check_mod_type_wf` to avoid a scenario where rustc quits before checking all the types for representability. This also removes the check from rustdoc, which is alright AFAIK.
r? ``@cjgillot``
Use correct location for type tests in promoted constants
Previously we forgot to remap the location in a type test collected when visiting the body of a promoted constant back to the usage location, causing an ICE when trying to get span information for that type test.
Fixes https://github.com/rust-lang/rust/issues/102117
Migrate rustc_passes diagnostics
Picks up abandoned work from https://github.com/rust-lang/rust/pull/100870
I would like to do this collaboratively, as there is a lot of work! Here's the process:
- Comment below that you are willing to help and I will add you as a collaborator to my `rust` fork (that gives you write access)
- Indicate which file/task you would like to work on (so we don't duplicate work) from the list below
- Do the work, push up a commit, comment that you're done with that file/task
- Repeat until done 😄
### Files to Migrate (in `compiler/rustc_passes/src/`)
- [x] check_attr.rs ``@CleanCut``
- [x] check_const.rs ``@CleanCut``
- [x] dead.rs ``@CleanCut``
- [x] debugger_visualizer.rs ``@CleanCut``
- [x] diagnostic_items.rs ``@CleanCut``
- [x] entry.rs ``@CleanCut``
- [x] lang_items.rs ``@CleanCut``
- [x] layout_test.rs ``@CleanCut``
- [x] lib_features.rs ``@CleanCut``
- [x] ~liveness.rs~ ``@CleanCut`` Nothing to do
- [x] loops.rs ``@CleanCut``
- [x] naked_functions.rs ``@CleanCut``
- [x] stability.rs ``@CleanCut``
- [x] weak_lang_items.rs ``@CleanCut``
### Tasks
- [x] Rebase on current `master` ``@CleanCut``
- [x] Review work from [the earlier PR](https://github.com/rust-lang/rust/pull/100870) and make sure it all looks good
- [x] compiler/rustc_error_messages/locales/en-US/passes.ftl ``@CleanCut``
- [x] compiler/rustc_passes/src/check_attr.rs ``@CleanCut``
- [x] compiler/rustc_passes/src/errors.rs ``@CleanCut``
- [x] compiler/rustc_passes/src/lang_items.rs ``@CleanCut``
- [x] compiler/rustc_passes/src/lib.rs ``@CleanCut``
- [x] compiler/rustc_passes/src/weak_lang_items.rs ``@CleanCut``
Remove `TokenStreamBuilder`
`TokenStreamBuilder` is used to combine multiple token streams. It can be removed, leaving the code a little simpler and a little faster.
r? `@Aaron1011`
Migrate `codegen_ssa` to diagnostics structs - [Part 1]
Initial migration of `codegen_ssa`. Going to split this crate migration in at least two PRs in order to avoid a huge PR and to quick off some questions around:
1. Translating messages from "external" crates.
2. Interfacing with OS messages.
3. Adding UI tests while migrating diagnostics.
_See comments below._
Check uniqueness of impl items by trait item when applicable.
When checking uniqueness of item names in impl blocks, we currently use the same definition of hygiene as for toplevel items. This means that a plain item and one generated by a macro 2.0 do not collide.
This hygiene rule does not match with how impl items resolve to associated trait items. As a consequence, we misdiagnose the trait impls.
This PR proposes to consider that trait impl items are uses of the corresponding trait items during resolution, instead of checking for duplicates later. An error is emitted when a trait impl item is used twice.
There should be no stable breakage, since macros 2.0 are still unstable.
r? ``@petrochenkov``
cc ``@RalfJung``
Fixes https://github.com/rust-lang/rust/issues/71614.
Move lifetime resolution module to rustc_hir_analysis.
Now that lifetime resolution has been removed from it, this file has nothing to do in `rustc_resolve`. It's purpose is to compute Debruijn indices for lifetimes, so let's put it in type collection.
suggest candidates for unresolved import
Currently we prompt suggestion of candidates(help notes of `use xxx::yyy`) for names which cannot be resolved, but we don't do that for import statements themselves that couldn't be resolved. It seems reasonable to add candidate help information for these statements as well.
Fixes#102711
Following the approach taken in earlier commits to separate formatting
initialization from use in the subdiagnostic derive, simplify the
diagnostic derive by removing the field-ordering logic that previously
solved this problem.
Signed-off-by: David Wood <david.wood@huawei.com>
Diagnostic derives have previously had to take special care when
ordering the generated code so that fields were not used after a move.
This is unlikely for most fields because a field is either annotated
with a subdiagnostic attribute and is thus likely a `Span` and copiable,
or is a argument, in which case it is only used once by `set_arg`
anyway.
However, format strings for code in suggestions can result in fields
being used after being moved if not ordered carefully. As a result, the
derive currently puts `set_arg` calls last (just before emission), such
as:
```rust
let diag = { /* create diagnostic */ };
diag.span_suggestion_with_style(
span,
fluent::crate::slug,
format!("{}", __binding_0),
Applicability::Unknown,
SuggestionStyle::ShowAlways
);
/* + other subdiagnostic additions */
diag.set_arg("foo", __binding_0);
/* + other `set_arg` calls */
diag.emit();
```
For eager translation, this doesn't work, as the message being
translated eagerly can assume that all arguments are available - so
arguments _must_ be set first.
Format strings for suggestion code are now separated into two parts - an
initialization line that performs the formatting into a variable, and a
usage in the subdiagnostic addition.
By separating these parts, the initialization can happen before
arguments are set, preserving the desired order so that code compiles,
while still enabling arguments to be set before subdiagnostics are
added.
```rust
let diag = { /* create diagnostic */ };
let __code_0 = format!("{}", __binding_0);
/* + other formatting */
diag.set_arg("foo", __binding_0);
/* + other `set_arg` calls */
diag.span_suggestion_with_style(
span,
fluent::crate::slug,
__code_0,
Applicability::Unknown,
SuggestionStyle::ShowAlways
);
/* + other subdiagnostic additions */
diag.emit();
```
Signed-off-by: David Wood <david.wood@huawei.com>
Add support for `eager` argument to the `subdiagnostic` attribute which
generates a call to `eager_subdiagnostic`.
Signed-off-by: David Wood <david.wood@huawei.com>
Add variant of `DiagnosticMessage` for eagerly translated messages
(messages in the target language which don't need translated by the
emitter during emission). Also adds `eager_subdiagnostic` function which
is intended to be invoked by the diagnostic derive for subdiagnostic
fields which are marked as needing eager translation.
Signed-off-by: David Wood <david.wood@huawei.com>
`AddToDiagnostic::add_to_diagnostic_with` is similar to the previous
`AddToDiagnostic::add_to_diagnostic` but takes a function that can be
used by the caller to modify diagnostic messages originating from the
subdiagnostic (such as performing translation eagerly).
`add_to_diagnostic` now just calls `add_to_diagnostic_with` with an
empty closure.
Signed-off-by: David Wood <david.wood@huawei.com>
Eager translation will enable subdiagnostics to be translated multiple
times with different arguments - this requires the ability to replace
the value of one argument with a new value, which is better suited to a
`HashMap` than the previous storage, a `Vec`.
Signed-off-by: David Wood <david.wood@huawei.com>
Uplift `clippy::for_loops_over_fallibles` lint into rustc
This PR, as the title suggests, uplifts [`clippy::for_loops_over_fallibles`] lint into rustc. This lint warns for code like this:
```rust
for _ in Some(1) {}
for _ in Ok::<_, ()>(1) {}
```
i.e. directly iterating over `Option` and `Result` using `for` loop.
There are a number of suggestions that this PR adds (on top of what clippy suggested):
1. If the argument (? is there a better name for that expression) of a `for` loop is a `.next()` call, then we can suggest removing it (or rather replacing with `.by_ref()` to allow iterator being used later)
```rust
for _ in iter.next() {}
// turns into
for _ in iter.by_ref() {}
```
2. (otherwise) We can suggest using `while let`, this is useful for non-iterator, iterator-like things like [async] channels
```rust
for _ in rx.recv() {}
// turns into
while let Some(_) = rx.recv() {}
```
3. If the argument type is `Result<impl IntoIterator, _>` and the body has a `Result<_, _>` type, we can suggest using `?`
```rust
for _ in f() {}
// turns into
for _ in f()? {}
```
4. To preserve the original behavior and clear intent, we can suggest using `if let`
```rust
for _ in f() {}
// turns into
if let Some(_) = f() {}
```
(P.S. `Some` and `Ok` are interchangeable depending on the type)
I still feel that the lint wording/look is somewhat off, so I'll be happy to hear suggestions (on how to improve suggestions :D)!
Resolves#99272
[`clippy::for_loops_over_fallibles`]: https://rust-lang.github.io/rust-clippy/master/index.html#for_loops_over_fallibles
Add missing documentation for FileNameDisplayPreference variants
Took me a while to find the information when I needed it so hopefully it should save some time for the next ones.
r? ``@thomcc``
Elaborate trait ref to compute object safety.
instead of building them manually from supertraits and associated items.
This allows to have the correct substs for GATs.
Fixes https://github.com/rust-lang/rust/issues/102751
rename `ImplItemKind::TyAlias` to `ImplItemKind::Type`
The naming of this variant seems inconsistent given that this is not really a "type alias", and the associated type variant for `TraitItemKind` is just called `Type`.
Show let-else suggestion on stable.
The E0005 error message has a suggestion to use let-else. Now that let-else is stabilized, I think this message should be included on non-nightly toolchains. I suspect this was just an oversight from #93628. [`E0005.stderr`](be1c7aad72/src/test/ui/error-codes/E0005.stderr (L22-L25)) contains an example of what this suggestion looks like.
I refactored the code:
- Removed handling of methods, as it felt entirely unnecessary
- Removed clippy utils (obviously...)
- Used some shiny compiler features
(let-else is very handy for lints 👀)
- I also renamed the lint to `for_loop_over_fallibles` (note: no `s`).
I'm not sure what's the naming convention here, so maybe I'm wrong.
don't ICE when normalizing closure input tys
We were ICEing while rendering diagnostics because `universe_causes` is expected to track every universe created in the typeck's infcx.
`normalize_and_add_constraints` doesn't update `universe_causes`
when creating new universes, causing an ICE. Remove it!
Add spans to better track normalization constraints.
Fix couple places where `universe_causes` is not updated correctly to
track newly added universes.
Fixes#102800
~Fixess #99665~ (UPDATE: no longer true; the issue has a different failure path than when this PR was created and should be fixed by #101708, but the changes in this PR are still correct and should prevent potential future ICEs)
Remove `DefId` from some `SelectionCandidate` variants
They are both from `obligation.predicate.def_id()`, which do not need to be on the `SelectionCandidate`.
cc ````@lcnr```` ````@compiler-errors````
Fix MIR inlining of asm_unwind
The MIR inlining currently doesn't handle inline asm's unwind edge correctly.
This code will cause ICE:
```rust
struct D;
impl Drop for D {
fn drop(&mut self) {}
}
#[inline(always)]
fn foo() {
let _d = D;
unsafe { std::arch::asm!("", options(may_unwind)) };
}
pub fn main() {
foo();
}
```
This PR fixes this issue. I also take the opportunity to extract common code into a method.
Remove `mir::CastKind::Misc`
As discussed in #97649 `mir::CastKind::Misc` is not clear, this PR addresses that by creating a new enum variant for every valid cast.
r? ````@oli-obk````
Rewrite representability
* Improve placement of `Box` in the suggestion
* Multiple items in a cycle emit 1 error instead of an error for each item in the cycle
* Introduce `representability` query to avoid traversing an item every time it is used.
* Also introduce `params_in_repr` query to avoid traversing generic items every time it is used.
`normalize_and_add_constraints` doesn't add entries in `universe_causes`
when creating new universes, causing an ICE. Remove it!
Add spans to track normalization constraints.
Fix couple places where `universe_causes` is not updated correctly to
track newly added universes.