Detect cycle errors hidden by opaques during monomorphization
Opaque types may reveal to projections, which themselves normalize to opaques. We don't currently normalize when checking that opaques are cyclical, and we may also not know that the opaque is cyclical until monomorphization (see `tests/ui/type-alias-impl-trait/mututally-recursive-overflow.rs`).
Detect cycle errors in `normalize_projection_ty` and report a fatal overflow (in the old solver). Luckily, this is already detected as a fatal overflow in the new solver.
Fixes#112047
rustc_target/riscv: Fix passing of transparent unions with only one non-ZST member
This ensures that `MaybeUninit<T>` has the same ABI as `T` when passed through an `extern "C"` function.
Fixes https://github.com/rust-lang/rust/issues/115481.
r? `@RalfJung`
This function is now used to check `#[panic_handler]`, `start` lang item, `main`, `#[start]` and intrinsic functions.
The diagnosis produced are now closer to the ones produced by trait/impl method signature mismatch.
Don't complain on a single non-exhaustive 1-ZST
r? RalfJung, though you mentioned being busy, so feel free to reassign.
This doesn't actually attempt to make the diagnostic better, so when we have two non-exhaustive 1-ZSTs in a struct, we still just point to one. 🤷Fixes#115922
Explain HRTB + infer limitations of old solver
Add a helpful message when we hit the limitation of the old trait solver where we don't properly normalize GATs with infer vars + bound vars, leading to too-eagerly reporting trait errors that would be later satisfied due to inference.
Make `TyKind::Adt`'s `Debug` impl be more pretty
Currently `{:?}` on `Ty` for a `TyKind::Adt` would print as `Adt(Foo, [])`. This PR changes it to be `Foo` when there are no generics or `Foo<T>`/`Foo<T, U>` when there _are_ generics. Example from debug log:
`├─0ms DEBUG rustc_hir_analysis::astconv return=Bar<T/#0, U/#1>`
I should have done this in my initial PR for a prettier TyKind: Debug impl but I thought I would need to be accessing generics_of to figure out where in the "path" the generics would have to go??? but no, adts literally only have a single place the generics can go (on the end). Feel a bit silly about this :)
r? `@oli-obk`
Avoid blessing cargo deps's source code in ui tests
Before this PR, the source code of dependencies was included in UI test error messages whenever possible. Unfortunately, "whenever possible" means in some cases the source code wouldn't be injected, resulting in a test failure.
One such case is when `$CARGO_HOME` is remapped to something that is not present on disk [^1]. As the remapped path doesn't exist on disk, the source code wouldn't be showed in `tests/ui/issues/issue-21763.rs`:
```diff
= note: required for `hashbrown::raw::RawTable<(Rc<()>, Rc<()>)>` to implement `Send`
note: required because it appears within the type `HashMap<Rc<()>, Rc<()>, RandomState>`
--> $HASHBROWN_SRC_LOCATION
- |
-LL | pub struct HashMap<K, V, S = DefaultHashBuilder, A: Allocator + Clone = Global> {
- | ^^^^^^^
note: required because it appears within the type `HashMap<Rc<()>, Rc<()>>`
--> $SRC_DIR/std/src/collections/hash/map.rs:LL:COL
note: required by a bound in `foo`
```
This PR fixes the problem by always hiding dependencies source code in the error messages generated during UI tests. This is implemented with a new internal flag, `-Z ignore-directory-in-diagnostics-source-blocks=$path`, which compiletest passes during UI tests. Once this is merged, remapping the Cargo home will be supported.
This PR is best reviewed commit-by-commit.
[^1]: After being puzzled for a bit, I discovered why this never impacted `rust-lang/rust`: we don't remap `$CARGO_HOME` 😅. Instead, we set `$CARGO_HOME` to `/cargo` in CI, which sort-of-but-not-really achieves the same effect.
move required_consts check to general post-mono-check function
This factors some code that is common between the interpreter and the codegen backends into shared helper functions. Also as a side-effect the interpreter now uses the same `eval` functions as everyone else to get the evaluated MIR constants.
Also this is in preparation for another post-mono check that will be needed for (the current hackfix for) https://github.com/rust-lang/rust/issues/115709: ensuring that all locals are dynamically sized.
I didn't expect this to change diagnostics, but it's just cycle errors that change.
r? `@oli-obk`
repr(transparent): it's fine if the one non-1-ZST field is a ZST
This code currently gets rejected:
```rust
#[repr(transparent)]
struct MyType([u16; 0])
```
That clearly seems like a bug to me: `repr(transparent)` [got defined ](https://github.com/rust-lang/rust/issues/77841#issuecomment-716575747) as having any number of 1-ZST fields plus optionally one more field; `MyType` clearly satisfies that definition.
This PR changes the `repr(transparent)` logic to actually match that definition.
Rollup of 6 pull requests
Successful merges:
- #114965 (Remove Drop impl of mpsc Receiver and (Sync)Sender)
- #115434 (make `Debug` impl for `ascii::Char` match that of `char`)
- #115477 (Stabilize the `Saturating` type)
- #115611 (add diagnostic for raw identifiers in format string)
- #115654 (improve PassMode docs)
- #115862 (Migrate `compiler/rustc_hir_typeck/src/callee.rs` to translatable diagnostics)
r? `@ghost`
`@rustbot` modify labels: rollup
add diagnostic for raw identifiers in format string
Format strings don't support raw identifiers (e.g. `format!("{r#type}")`), but they do support keywords in the format string directly (e.g. `format!("{type}")`). This PR improves the error output when attempting to use a raw identifier in a format string and adds a machine-applicable suggestion to remove the `r#`.
fixes https://github.com/rust-lang/rust/issues/115466
`#[diagnostic::on_unimplemented]` without filters
This commit adds support for a `#[diagnostic::on_unimplemented]` attribute with the following options:
* `message` to customize the primary error message
* `note` to add a customized note message to an error message
* `label` to customize the label part of the error message
The relevant behavior is specified in [RFC-3366](https://rust-lang.github.io/rfcs/3366-diagnostic-attribute-namespace.html)
impl Step for IP addresses
ACP: rust-lang/libs-team#235
Note: since this is insta-stable, it requires an FCP.
Separating out from the bit operations PR since it feels logically disjoint, and so their FCPs can be separate.
closure field capturing: don't depend on alignment of packed fields
This fixes the closure field capture part of https://github.com/rust-lang/rust/issues/115305: field capturing always stops at projections into packed structs, no matter the alignment of the field. This means changing a private field type from `u8` to `u64` can never change how closures capture fields, which is probably what we want.
Here's an example where, before this PR, changing the type of a private field in a repr(Rust) struct can change the output of a program:
```rust
#![allow(dead_code)]
mod m {
// before patch
#[derive(Default)]
pub struct S1(u8);
// after patch
#[derive(Default)]
pub struct S2(u64);
}
struct NoisyDrop;
impl Drop for NoisyDrop {
fn drop(&mut self) {
eprintln!("dropped!");
}
}
#[repr(packed)]
struct MyType {
field: m::S1, // output changes when this becomes S2
other_field: NoisyDrop,
third_field: Vec<()>,
}
fn test(r: MyType) {
let c = || {
let _val = std::ptr::addr_of!(r.field);
let _val = r.third_field;
};
drop(c);
eprintln!("before dropping");
}
fn main() {
test(MyType {
field: Default::default(),
other_field: NoisyDrop,
third_field: Vec::new(),
});
}
```
Of course this is a breaking change for the same reason that doing field capturing in the first place was a breaking change. Packed fields are relatively rare and depending on drop order is relatively rare, so I don't expect this to have much impact, but it's hard to be sure and even a crater run will only tell us so much.
Also see the [nomination comment](https://github.com/rust-lang/rust/pull/115315#issuecomment-1702807825).
Cc `@rust-lang/wg-rfc-2229` `@ehuss`
Make useless_ptr_null_checks smarter about some std functions
This teaches the `useless_ptr_null_checks` lint that some std functions can't ever return null pointers, because they need to point to valid data, get references as input, etc.
This is achieved by introducing an `#[rustc_never_returns_null_ptr]` attribute and adding it to these std functions (gated behind bootstrap `cfg_attr`).
Later on, the attribute could maybe be used to tell LLVM that the returned pointer is never null. I don't expect much impact of that though, as the functions are pretty shallow and usually the input data is already never null.
Follow-up of PR #113657Fixes#114442
Fallback effects even if types also fallback
`||` is short circuiting, so if we do ty/int var fallback, we *don't* do effect fallback 😸
r? `@fee1-dead` or `@oli-obk`
Fixes#115791Fixes#115842
Improve invalid let expression handling
- Move all of the checks for valid let expression positions to parsing.
- Add a field to ExprKind::Let in AST/HIR to mark whether it's in a valid location.
- Suppress some later errors and MIR construction for invalid let expressions.
- Fix a (drop) scope issue that was also responsible for #104172.
Fixes#104172Fixes#104868
Paper over an accidental regression
r? types
cc https://github.com/rust-lang/rust/issues/115781 (do not close issue until beta backport has been performed)
The PR reasons are explained with comments in the source.
In order to keep the diff simple, this PR effectively reverts https://github.com/rust-lang/rust/pull/113661, but only for RPITs. I will submit a follow up PR that fixes this correctly instead of just disabling the newly added check for RPITs. This PR should be significantly easier to review for beta backport
Properly consider binder vars in `HasTypeFlagsVisitor`
Given a PolyTraitRef like `for<'a> Ty: Trait` (where neither `Ty` nor `Trait` mention `'a`), we do *not* return true for `.has_type_flags(TypeFlags::HAS_LATE_BOUND)`, even though binders are supposed to act as if they have late-bound vars even if they don't mention them in their bound value: 31ae3b2bdb. This is because we use `HasTypeFlagsVisitor`, which only computes the type flags for `Ty`, `Const` and `Region` and `Predicates`, and we consequently skip any binders (and setting flags for their vars) that are not contained in one of these types.
This ends up causing a problem, because when we call `TyCtxt::erase_regions` (which both erases regions *and* anonymizes bound vars), we will skip such a PolyTraitRef, not anonymizing it, and therefore not making it structurally equal to other binders. This breaks vtable computations.
This PR computes the flags for all binders we enter in `HasTypeFlagsVisitor` if we're looking for `TypeFlags::HAS_LATE_BOUND` (or `TypeFlags::HAS_{RE,TY,CT}_LATE_BOUND`).
Fixes#115807
Fix the error message for `#![feature(no_coverage)]`
When #114656 was written, the feature flag to replace `no_coverage` was originally spelled `coverage`, but it was eventually changed to `coverage_attribute` instead.
That update happened to miss this error message in `removed.rs`, and unfortunately I only noticed just *after* the original PR was approved and merged.
cc ``@bossmc`` (original author) ``@oli-obk`` (original reviewer)
``@rustbot`` label +A-code-coverage
some ConstValue refactoring
In particular, use AllocId instead of Allocation in ConstValue::ByRef. This helps avoid redundant AllocIds when a `ByRef` constant gets put back into the interpreter.
r? `@oli-obk`
Fixes https://github.com/rust-lang/rust/issues/105536
Rework `no_coverage` to `coverage(off)`
As discussed at the tail of https://github.com/rust-lang/rust/issues/84605 this replaces the `no_coverage` attribute with a `coverage` attribute that takes sub-parameters (currently `off` and `on`) to control the coverage instrumentation.
Allows future-proofing for things like `coverage(off, reason="Tested live", issue="#12345")` or similar.
cleanup leftovers of const_err lint
Some code / comments seem to not have been updated when const_err was turned into a hard error, so we can do a bit of cleanup here.
r? `@oli-obk`
- Add doc comment to new type
- Restore "only supported directly in conditions of `if` and `while` expressions" note
- Rename variant with clearer name
This commit adds support for a `#[diagnostic::on_unimplemented]`
attribute with the following options:
* `message` to customize the primary error message
* `note` to add a customized note message to an error message
* `label` to customize the label part of the error message
Co-authored-by: León Orell Valerian Liehr <me@fmease.dev>
Co-authored-by: Michael Goulet <michael@errs.io>
test ABI compatibility for some unsized types as well
and test for what `DispatchFromDyn` needs.
Also I ran this on a whole bunch of targets via Miri and added enough `cfg` to make it all work, as documentation for what does and doesn't currently work. (Most of those targets do not have their tests run on CI anyway.)
Here's the shell rune I used for that:
```
for TARGET in x86_64-unknown-linux-gnu x86_64-pc-windows-gnu aarch64-unknown-linux-gnu s390x-unknown-linux-gnu mips64-unknown-linux-gnuabi64 sparc64-unknown-linux-gnu powerpc64-unknown-linux-gnu powerpc64le-unknown-linux-gnu riscv64gc-unknown-linux-gnu loongarch64-unknown-linux-gnu wasm32-unknown-unknown; do
BOOTSTRAP_SKIP_TARGET_SANITY=1 ./x.py run miri --stage 0 --args tests/ui/abi/compatibility.rs --target $TARGET;
done
```
Rollup of 8 pull requests
Successful merges:
- #115548 (Extract parallel operations in `rustc_data_structures::sync` into a new `parallel` submodule)
- #115591 (Add regression test for LLVM 17-rc3 miscompile)
- #115631 (Don't ICE when computing ctype's `repr_nullable_ptr` for possibly-unsized ty)
- #115708 (fix homogeneous_aggregate not ignoring some ZST)
- #115730 (Some more small driver refactors)
- #115749 (Allow loading the SMIR for constants and statics)
- #115757 (Add a test for #108030)
- #115761 (Update books)
r? `@ghost`
`@rustbot` modify labels: rollup
fix homogeneous_aggregate not ignoring some ZST
This is an ABI-breaking change, because it fixes bugs in our ABI code. I'm not sure what that means for this PR, we don't really have a process for such changes, do we? I can only hope nobody relied on the old buggy behavior.
Fixes https://github.com/rust-lang/rust/issues/115664
Don't ICE when computing ctype's `repr_nullable_ptr` for possibly-unsized ty
We may not always be able to compute the layout of a type like `&T` when `T: ?Sized`, even if we're able to estimate its size skeleton.
r? davidtwco
Fixes#115628
Bubble up opaque <eq> opaque operations instead of picking an order
In case we are in `Bubble` mode (meaning every opaque type that is defined in the current crate is treated as if it were in its defining scope), we don't try to register an opaque type as the hidden type of another opaque type, but instead bubble up an obligation to equate them at the query caller site. Usually that means we have a `DefiningAnchor::Bind` and thus can reliably figure out whether an opaque type is in its defining scope. Where we can't, we'll error out, so the default is sound.
With this change we start using `AliasTyEq` predicates in the old solver, too.
fixes https://github.com/rust-lang/rust/issues/108498
But also regresses `tests/ui/impl-trait/anon_scope_creep.rs`. Our use of `Bubble` for `check_opaque_type_well_formed` is going to keep biting us.
r? `@lcnr` `@compiler-errors`
Previously some invalid let expressions would result in both a feature
error and a parsing error. Avoid this and ensure that we only emit the
parsing error when this happens.
There was an incomplete version of the check in parsing and a second
version in AST validation. This meant that some, but not all, invalid
uses were allowed inside macros/disabled cfgs. It also means that later
passes have a hard time knowing when the let expression is in a valid
location, sometimes causing ICEs.
- Add a field to ExprKind::Let in AST/HIR to mark whether it's in a
valid location.
- Suppress later errors and MIR construction for invalid let
expressions.
Improve diagnostic for generic params from outer items (E0401)
Generalize the wording of E0401 to talk about *outer items* instead of *outer functions* since the current phrasing is outdated. The outer item can be a function, constant, trait, ADT or impl block (see the new UI test for the more exotic examples).
Further, don't suggest introducing generic parameters to constant items unless the feature `generic_const_items` is enabled.
Lastly, make E0401 translatable while we're at it.
Fixes#115720.
Fix incorrect mutable suggestion information for binding in ref pattern like: `let &b = a;`
fixes#114896
I find we have to get pat_span but not local_decl.source_info.span for suggestion. In `let &b = a;` pat_span is &b. I think check `let &b = a` in hir to make sure it is hir::Node::Local(hir::Local {pat: hir::Pat{kind: hir::PatKind::Ref(....... can distinguish it from other situation, but I'm not sure.
If my processing method is not accurate, please guide me to modify it, thank you.
r? `@davidtwco`
The `Debug` impl for `Ty` just calls the `Display` impl for `Ty`. This
is surprising and annoying. In particular, it means `Debug` doesn't show
as much information as `Debug` for `TyKind` does. And `Debug` is used in
some user-facing error messages, which seems bad.
This commit changes the `Debug` impl for `Ty` to call the `Debug` impl
for `TyKind`. It also does a number of follow-up changes to preserve
existing output, many of which involve inserting
`with_no_trimmed_paths!` calls. It also adds `Display` impls for
`UserType` and `Canonical`.
Some tests have changes to expected output:
- Those that use the `rustc_abi(debug)` attribute.
- Those that use the `EMIT_MIR` annotation.
In each case the output is slightly uglier than before. This isn't
ideal, but it's pretty weird (particularly for the attribute) that the
output is using `Debug` in the first place. They're fairly obscure
attributes (I hadn't heard of them) so I'm not worried by this.
For `async-is-unwindsafe.stderr`, there is one line that now lacks a
full path. This is a consistency improvement, because all the other
mentions of `Context` in this test lack a path.
The lint panicked for an input like 'extern "C" fn(Option<&<T as FooTrait>::FooType>)' because the type T therein cannot be normalized. The normalization failure caused SizeSkeleton::compute() to return an error and trigger a panic in the unwrap().
Fix sanitize/cfg.rs test
* Move needs-sanitizer conditions to specific revisions that require them (otherwise the conditions are mutually exclusive with needs-sanitizer-kcfi and test is always ignored).
* Add missing revisions
Improve "associated type not found" diagnostics
```rs
use core::ops::Deref;
fn foo<T>() where T: Deref<Output = u32> {}
```
Before:
```
error[E0220]: associated type `Output` not found for `Deref`
--> E0220.rs:5:28
|
5 | fn foo<T>() where T: Deref<Output = u32> {}
| ^^^^^^ associated type `Output` not found
```
After:
```
error[E0220]: associated type `Output` not found for `Deref`
--> E0220.rs:5:28
|
5 | fn foo<T>() where T: Deref<Output = u32> {}
| ^^^^^^ help: `Deref` has the following associated type: `Target`
```
---
`@rustbot` label +A-diagnostics +D-papercut
Rollup of 6 pull requests
Successful merges:
- #104299 (Clarify stability guarantee for lifetimes in enum discriminants)
- #115088 (Fix Step Skipping Caused by Using the `--exclude` Option)
- #115201 (rustdoc: list matching impls on type aliases)
- #115633 (Lint node for `PRIVATE_BOUNDS`/`PRIVATE_INTERFACES` is the item which names the private type)
- #115638 (`-Cllvm-args` usability improvement)
- #115643 (fix: return early when has tainted in mir-lint)
r? `@ghost`
`@rustbot` modify labels: rollup
* Move needs-sanitizer conditions to specific revisions that
require them (otherwise the conditions are mutually exclusive
with needs-sanitizer-kcfi and test is always ignored).
* Add missing revisions
fix: return early when has tainted in mir-lint
Fixes#115203
`a[..]` is of indeterminate size, it had been reported error during borrow check, therefore we skip the mir lint process.
Lint node for `PRIVATE_BOUNDS`/`PRIVATE_INTERFACES` is the item which names the private type
The HIR that the `PRIVATE_BOUNDS` lint should be attached to is the item that has the *bounds*, not the private type. This PR also aligns this behavior with the `EXPORTED_PRIVATE_DEPENDENCIES` lint, which also requires putting the `allow` on the item that names the private type.
Fixes#115475
r? petrochenkov
diagnostics: add test case for trait bounds diagnostic
Closes#82038
It was fixed by https://github.com/rust-lang/rust/pull/89580, a wide-reaching obligation tracking improvement. This commit adds a test case.
Don't suggest dereferencing to unsized type
Rudimentary check that the self type is Sized. I don't really like any of this diagnostics code -- it's really messy and also really prone to false positives and negatives, but oh well.
Fixes#115569
Print the path of a return-position impl trait in trait when `return_type_notation` is enabled
When we're printing a return-position impl trait in trait, we usually just print it like an opaque. This is *usually* fine, but can be confusing when using `return_type_notation`. Print the path of the method from where the RPITIT originates when this feature gate is enabled.
Don't require `Drop` for `[PhantomData<T>; N]` where `N` and `T` are generic, if `T` requires `Drop`
fixes https://github.com/rust-lang/rust/issues/115403
fixes https://github.com/rust-lang/rust/issues/115410
This was accidentally regressed in https://github.com/rust-lang/rust/pull/114134, because it was accidentally stabilized in #102204 (cc `@rust-lang/lang,` seems like an innocent stabilization, considering this PR is more of a bugfix than a feature).
While we have a whole month to beta backport this change before the regression hits stable, I'd still prefer not to go through an FCP on this PR (which fixes a regression), if T-lang wants an FCP, I can can open an issue about the change itself.
Stabilize `PATH` option for `--print KIND=PATH`
This PR propose stabilizing the `PATH` option for `--print KIND=PATH`. This option was previously added in https://github.com/rust-lang/rust/pull/113780 (as insta-stable before being un-stablized in https://github.com/rust-lang/rust/pull/114139).
Description of the `PATH` option:
> A filepath may optionally be specified for each requested information kind, in the format `--print KIND=PATH`, just like for `--emit`. When a path is specified, information will be written there instead of to stdout.
------
Description of the original PR [\[link\]](https://github.com/rust-lang/rust/pull/113780#issue-1807080607):
> **Support --print KIND=PATH command line syntax**
>
> As is already done for `--emit KIND=PATH` and `-L KIND=PATH`.
>
> In the discussion of https://github.com/rust-lang/rust/pull/110785, it was pointed out that `--print KIND=PATH` is nicer than trying to apply the single global `-o path` to `--print`'s output, because in general there can be multiple print requests within a single rustc invocation, and anyway `-o` would already be used for a different meaning in the case of `link-args` and `native-static-libs`.
>
> I am interested in using `--print cfg=PATH` in Buck2. Currently Buck2 works around the lack of support for `--print KIND=PATH` by [indirecting through a Python wrapper script](d43cf3a51a/prelude/rust/tools/get_rustc_cfg.py) to redirect rustc's stdout into the location dictated by the build system.
>
> From skimming Cargo's usages of `--print`, it definitely seems like it would benefit from `--print KIND=PATH` too. Currently it is working around the lack of this by inserting `--crate-name=___ --print=crate-name` so that it can look for a line containing `___` as a delimiter between the 2 other `--print` informations it actually cares about. This is commented as a "HACK" and "abuse". 31eda6f7c3/src/cargo/core/compiler/build_context/target_info.rs (L242)
-----
cc `@dtolnay`
r? `@jackh726`
Description of the `PATH` option:
> A filepath may optionally be specified for each requested information
> kind, in the format `--print KIND=PATH`, just like for `--emit`. When
> a path is specified, information will be written there instead of to
> stdout.
Implement refinement lint for RPITIT
Implements a lint that warns against accidentally refining an RPITIT in an implementation. This is not a hard error, and can be suppressed with `#[allow(refining_impl_trait)]`, since this behavior may be desirable -- the lint just serves as an acknowledgement from the impl author that they understand that the types they write in the implementation are an API guarantee.
This compares bounds syntactically, not semantically -- semantic implication is more difficult and essentially relies on adding the ability to keep the RPITIT hidden in the trait system so that things can be proven about the type that shows up in the impl without its own bounds leaking through, either via a new reveal mode or something else. This was experimentally implemented in #111931.
Somewhat opinionated choices:
1. Putting the lint behind `refining_impl_trait` rather than a blanket `refine` lint. This could be changed, but I like keeping the lint specialized to RPITITs so the explanation can be tailored to it.
2. This PR does not include the `#[refine]` attribute or the feature gate, since it's kind of orthogonal and can be added in a separate PR.
r? `@oli-obk`
Lint on invalid usage of `UnsafeCell::raw_get` in reference casting
This PR proposes to take into account `UnsafeCell::raw_get` method call for non-Freeze types for the `invalid_reference_casting` lint.
The goal of this is to catch those kind of invalid reference casting:
```rust
fn as_mut<T>(x: &T) -> &mut T {
unsafe { &mut *std::cell::UnsafeCell::raw_get(x as *const _ as *const _) }
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
}
```
r? `@est31`
fix#115348fix#115348
It looks that:
- In `rustc_mir_build::build`, the body of function will not be built, when the `tcx.check_match(def)` fails due to `non-exhaustive patterns`
- In `rustc_mir_transform::check_unsafety`, the `UnsafetyChecker` collects all `used_unsafe_blocks` in the MIR of a function, and the `UnusedUnsafeVisitor` will visit all `UnsafeBlock`s in the HIR and collect `unused_unsafes`, which are not contained in `used_unsafe_blocks`, and report `unnecessary_unsafe`s
- So the unsafe block in the issue example code will be reported as `unnecessary_unsafe`.
Add explanatory note to 'expected item' error
Fixes#113110
It changes the diagnostic from this:
```
error: expected item, found `5`
--> ../test.rs:1:1
|
1 | 5
| ^ expected item
```
to this:
```
error: expected item, found `5`
--> ../test.rs:1:1
|
1 | 5
| ^ expected item
|
= note: items are things that can appear at the root of a module
= note: for a full list see https://doc.rust-lang.org/reference/items.html
```
Fix error report for size overflow from transmute
Fixes#115402
The span in the error reporting always points to the `dst`, this is an old issue, I may open another PR to fix it.
Make if let guard parsing consistent with normal guards
- Add tests that struct expressions are not allowed in `if let` and `while let` (no change, consistent with `if` and `while`)
- Allow struct expressions in `if let` guards (consistent with `if` guards).
r? `@cjgillot`
Closes#93817
cc #51114
Rollup of 5 pull requests
Successful merges:
- #115353 (Emit error instead of ICE when optimized MIR is missing)
- #115488 (Take `&mut Results` in `ResultsVisitor`)
- #115492 (Allow `large_assignments` for Box/Arc/Rc initialization)
- #115519 (Don't ICE on associated type projection without feature gate in new solver)
- #115534 (Expose more information with DefId in smir)
r? `@ghost`
`@rustbot` modify labels: rollup
Don't ICE on associated type projection without feature gate in new solver
Self-explanatory, we should avoid ICEs when the feature gate is not enabled. Continue to ICE when the feature gate *is* enabled, though.
Fixes#115500
Allow `large_assignments` for Box/Arc/Rc initialization
Does the `stop linting in box/arc initialization` task of #83518.
r? `@oli-obk` who is E-mentor.
Do not require associated types with Self: Sized to uphold bounds when confirming object candidate
RPITITs and associated types that have `Self: Sized` bounds are opted out of the `dyn Trait` well-formedness check that happens during confirmation. This ensures that we can actually *use* `dyn Trait`s that have associated types that, e.g., have GATs and RPITITs and other naughty things as long as those are opted-out of object safety via a `Self: Sized` bound.
Fixes#115464
This seems like a natural part of https://github.com/rust-lang/rust/pull/112319#issuecomment-1592574451, and I don't think needs re-litigation.
r? `@oli-obk`
Implement Step for ascii::Char
This allows iterating over ranges of `ascii::Char`, similarly to ranges of `char`.
Note that `ascii::Char` is still unstable, tracked in #110998.
Normally, variables with common linkage must be zero-initialized. In Rust,
common linkage variables that are not zero-initialized causes a crash in the
compiler backend.
This commit adds a test case to confirm this behavior, which will inform us if
it changes in the future.
Lower `Or` pattern without allocating place
cc `@azizghuloum` `@cjgillot`
Related to #111583 and #111644
While reviewing #111644, it occurs to me that while we directly lower conjunctive predicates, which are connected with `&&`, into the desirable control flow, today we don't directly lower the disjunctive predicates, which are connected with `||`, in the similar fashion. Instead, we allocate a place for the boolean temporary to hold the result of evaluating the `||` expression.
Usually I would expect optimization at later stages to "inline" the evaluation of boolean predicates into simple CFG, but #111583 is an example where `&&` is failing to be optimized away and the assembly shows that both the expensive operands are evaluated. Therefore, I would like to make a small change to make the CFG a bit more straight-forward without invoking the `as_temp` machinery, and plus avoid allocating the place to hold the boolean result as well.
Permit recursive weak type aliases
I saw #63097 and thought "we can do ~~better~~ funnier". So here it is. It's not useful, but it's certainly something. This may actually become feasible with lazy norm (so in 5 years (constant, not reducing over time)).
r? `@estebank`
cc `@GuillaumeGomez`
Capture lifetimes for associated type bounds destined to be lowered to opaques
Some associated type bounds get lowered to opaques, but they're not represented in the AST as opaques.
That means that we never collect lifetimes for them (`record_lifetime_params_for_impl_trait`) which are used currently for RPITITs, which capture all of their in-scope lifetimes[^1]. This means that the nested RPITITs that arise from some type like `impl Foo<Type: Bar>` (~> `impl Foo<Type = impl Bar>`) don't capture any lifetimes, leading to ICEs.
This PR makes sure we collect the lifetimes for associated type bounds as well, and make sure that they are set up correctly for opaque type lowering later.
Fixes#115360
[^1]: #114489
Work around ICE in diagnostics for local super-universes missing `UniverseInfo`s
In issue #114907, canonicalization of liveness dropck-outlives results (IIUC) encounters universes absent from the original query. Some local universes [are created](f3a1bae88c/compiler/rustc_infer/src/infer/canonical/query_response.rs (L417-L425)) for the mapping, but importantly, they won't have associated causes.
These missing `UniverseInfo`s can be [needed](f3a1bae88c/compiler/rustc_borrowck/src/diagnostics/region_errors.rs (L376)) during diagnostics, [causing the `IndexMap: key not found` ICE](d55522aad8/compiler/rustc_borrowck/src/region_infer/mod.rs (L2252)) seen in the issue.
This PR works around this by returning the suboptimal catch-all cause, to avoid the ICE. It does results in suboptimal diagnostics right now, but it's better than an ICE.
r? `@matthewjasper.`
Let me know if there's a good easy-ish way to fix this, but I believe that for some of these erroneous cases and diagnostics, that inference/canonicalization/higher-ranked subtyping/etc may not behave exactly the same with the new trait solver? If that's the case then it'd probably be best to wait a bit more to do the correct fix.
Fixes#114907.
cc `@aliemjay`
`rustc_layout_scalar_valid_range` makes ctors unsafe
We already validate this when we use the ctor in a call, e.g. `Variant(1)`, but not if we use the ctor as a fn ptr, e.g. `.map(Variant)`. The easiest way to fix the latter is (afaict) is by marking the ctor as unsafe itself.
Fixes#115284
Fix inlining with -Zalways-encode-mir
Only inline functions that are considered eligible for inlining
by the reachability pass.
This constraint was previously indirectly enforced by only exporting MIR
of eligible functions, but that approach doesn't work with
-Zalways-encode-mir enabled.
Add `ParallelGuard` type to handle unwinding in parallel sections
This adds a `ParallelGuard` type to handle unwinding in parallel sections instead of manually dealing with panics in each parallel operation. This also adds proper panic handling to the `join` operation.
cc `@SparrowLii`
This demonstrates the current behavior of adding lint form the command
line. generally the lint levels are ignored as the current implementation
unconditionally emit errors for those lints.
Don't suggest adding parentheses to call an inaccessible method.
Previously, code of this form would emit E0615 (attempt to use a method as a field), thus emphasizing the existence of private methods that the programmer probably does not care about. Now it ignores their existence instead, producing error E0609 (no field). The motivating example is:
```rust
let x = std::rc::Rc::new(());
x.inner;
```
which would previously mention the private method `Rc::inner()`, even though `Rc<T>` intentionally has no public methods so that it can be a transparent smart pointer for any `T`.
```rust
error[E0615]: attempted to take value of method `inner` on type `Rc<()>`
--> src/main.rs:3:3
|
3 | x.inner;
| ^^^^^ method, not a field
|
help: use parentheses to call the method
|
3 | x.inner();
| ++
```
With this change, it emits E0609 and no suggestion.
new solver: handle edge case of a recursion limit of 0
Apparently a recursion limit of 0 is possible/valid/useful/used/cute, the more you know 🌟 .
(It's somewhat interesting to me that the old solver seemingly handles this, and that the new solver currently requires a recursion limit of 2 here)
r? `@compiler-errors.`
Fixes#115351.
suggest removing `impl` in generic trait bound position
rustc already does this recovery in type param position (`<T: impl Trait>` -> `<T: Trait>`).
This PR also adds that suggestion in trait bound position (e.g. `where T: impl Trait` or `trait Trait { type Assoc: impl Trait; }`)
Make `get_return_block()` return `Some` only for HIR nodes in body
Fixes#114918
The issue occurred while compiling the following input:
```rust
fn uwu() -> [(); { () }] {
loop {}
}
```
It was caused by the code below trying to suggest a missing return type which resulted in a const eval cycle: 1bd043098e/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs (L68-L75)
The root cause was `get_return_block()` returning an `Fn` node for a node in the return type (i.e. the second `()` in the return type `[(); { () }]` of the input) although it is supposed to do so only for nodes that lie in the body of the function and return `None` otherwise (at least as per my understanding).
The PR fixes the issue by fixing this behaviour of `get_return_block()`.
parser: not insert dummy field in struct
Fixes#114636
This PR eliminates the dummy field, initially introduced in #113999, thereby enabling unrestricted use of `ident.unwrap()`. A side effect of this action is that we can only report the error of the first macro invocation field within the struct node.
An alternative solution might be giving a virtual name to the macro, but it appears more complex.(https://github.com/rust-lang/rust/issues/114636#issuecomment-1670228715). Furthermore, if you think https://github.com/rust-lang/rust/issues/114636#issuecomment-1670228715 is a better solution, feel free to close this PR.
Previously, the test code would emit E0615, thus revealing the existence
of private methods that the programmer probably does not care about.
Now it ignores their existence instead, producing error E0609 (no field).
The motivating example is:
```rust
let x = std::rc::Rc::new(());
x.inner;
```
which would previously mention the private method `Rc::inner()`, even
though `Rc<T>` intentionally has no public methods so that it can be a
transparent smart pointer for any `T`.
Make RPITITs capture all in-scope lifetimes
Much like #114616, this implements the lang team decision from this T-lang meeting on [opaque captures strategy moving forward](https://hackmd.io/sFaSIMJOQcuwCdnUvCxtuQ?view). This will be RFC'd soon, but given that RPITITs are a nightly feature, this shouldn't necessarily be blocked on that.
We unconditionally capture all lifetimes in RPITITs -- impl is not as simple as #114616, since we still need to duplicate RPIT lifetimes to make sure we reify any late-bound lifetimes in scope.
Closes#112194
More precisely detect cycle errors from type_of on opaque
Not sure if this still needs work. Just putting it up for initial impressions, since it seems that a few people are frustrated with the increased error verbosity due to #113320.
Essentially we introduce a new sub-query for `type_of` specifically for opaques which returns a value that is able to distinguish "has errors" from "due to cycle recovery".
Fixes#115188
r? `@oli-obk`
Avoid duplicate `large_assignments` lints
By checking for overlapping spans.
This PR does the "reduce noisiness" task in #83518.
r? `@oli-obk` who added E-mentor and E-help-wanted and wrote the initial code.
(The fix itself is in dc82736677. The two commits before that are just small refactorings.)