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>