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.)
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.
On the following example, point at `String` instead of the whole type:
```
error[E0277]: the trait bound `String: Copy` is not satisfied
--> $DIR/own-bound-span.rs:14:24
|
LL | let _: <S as D>::P<String>;
| ^^^^^^ the trait `Copy` is not implemented for `String`
|
note: required by a bound in `D::P`
--> $DIR/own-bound-span.rs:4:15
|
LL | type P<T: Copy>;
| ^^^^ required by this bound in `D::P`
```
remove some unnecessary ignore-debug clauses
ignore-debug is only needed when the debug assertions *in the standard library* somehow affect the test. This can happen with inlining but otherwise should be rare. ignore-debug is problematic since PR CI is only run with debug assertions.
r? `@cjgillot` since it looks like you added most of these
Allow explicit `#[repr(Rust)]`
This is identical to no `repr()` at all. For `Rust, packed` and `Rust, align(x)`, it should be the same as no `Rust` at all (as, afaik, `#[repr(align(16))]` uses the Rust ABI.)
The main use case for this is being able to explicitly say "I want to use the Rust ABI" in very very rare circumstances where the first obvious choice would be the C ABI yet is undesirable, which is already possible with functions as `extern "Rust"`. This would be useful for silencing https://github.com/rust-lang/rust-clippy/pull/11253. It's also more consistent with `extern`.
The lack of this also tripped me up a bit when I was new to Rust, as I expected this to be possible.
Fix ub-int-array test for big-endian platforms
As of commit 7767cbb3b0, the tests/ui/consts/const-eval/ub-int-array.rs test is failing on big-endian platforms (in particular s390x), as the stderr output contains a hex dump that depends on endianness.
Since this point intentionally verifies the hex dump to check the uninitialized byte markers, I think we should not simply standardize away the hex dump as is done with some of the other tests in this directory.
However, most of the test is already endian-independent. The only exception is one line of hex dump, which can also be made endian-independent by choosing appropriate constants in the source code.
Since the 32bit and 64bit stderr outputs were already (and remain) identical, I've merged them and removed the stderr-per-bitwidth marker.
Fixes (again) https://github.com/rust-lang/rust/issues/105383.
Move some ui tests to subdirectories
cc #73494
issue-2804 -> `macros/` (there's already the minified `issue-2804-2` there)
issue-17431 -> `structs-enums/struct-rec` and new `structs-enums/enum-rec` (original issue pertains to detection of recursive enums and structs)
issue-29181 and issue-66768 - moved according to the classifier tool
Suggest mutable borrow on read only for-loop that should be mutable
```
error[E0596]: cannot borrow `*test` as mutable, as it is behind a `&` reference
--> $DIR/suggest-mut-iterator.rs:22:9
|
LL | for test in &tests {
| ------ this iterator yields `&` references
LL | test.add(2);
| ^^^^ `test` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: use a mutable iterator instead
|
LL | for test in &mut tests {
| +++
```
Fix#114311.
Parse unnamed fields and anonymous structs or unions (no-recovery)
It is part of #114782 which implements #49804. Only parse anonymous structs or unions in struct field definition positions.
r? `@petrochenkov`
As of commit 7767cbb3b0,
the tests/ui/consts/const-eval/ub-int-array.rs test is
failing on big-endian platforms (in particular s390x),
as the stderr output contains a hex dump that depends
on endianness.
Since this point intentionally verifies the hex dump to
check the uninitialized byte markers, I think we should
not simply standardize away the hex dump as is done with
some of the other tests in this directory.
However, most of the test is already endian-independent.
The only exception is one line of hex dump, which can
also be made endian-independent by choosing appropriate
constants in the source code.
Since the 32bit and 64bit stderr outputs were already
(and remain) identical, I've merged them and removed
the stderr-per-bitwidth marker.
Fixes (again) https://github.com/rust-lang/rust/issues/105383.
Anonymous structs or unions are only allowed in struct field
definitions.
Co-authored-by: carbotaniuman <41451839+carbotaniuman@users.noreply.github.com>
```
error[E0596]: cannot borrow `*test` as mutable, as it is behind a `&` reference
--> $DIR/suggest-mut-iterator.rs:22:9
|
LL | for test in &tests {
| ------ this iterator yields `&` references
LL | test.add(2);
| ^^^^ `test` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: use a mutable iterator instead
|
LL | for test in &mut tests {
| +++
```
Address #114311.
Add support for `ptr::write`s for the `invalid_reference_casting` lint
This PR adds support for `ptr::write` and others for the `invalid_reference_casting` lint.
Detecting instances where instead of using the deref (`*`) operator to assign someone uses `ptr::write`, `ptr::write_unaligned` or `ptr::write_volatile`.
```rust
let data_len = 5u64;
std::ptr::write(
std::mem::transmute::<*const u64, *mut u64>(&data_len),
new_data_len,
);
```
r? ``@est31``
Don't do intra-pass validation on MIR shims
Fixes#114375
In the test that was committed, we end up generating the drop shim for `struct Foo` that looks like:
```
fn std::ptr::drop_in_place(_1: *mut Foo) -> () {
let mut _0: ();
bb0: {
goto -> bb5;
}
bb1: {
return;
}
bb2 (cleanup): {
resume;
}
bb3: {
goto -> bb1;
}
bb4 (cleanup): {
drop(((*_1).0: foo::WrapperWithDrop<()>)) -> [return: bb2, unwind terminate];
}
bb5: {
drop(((*_1).0: foo::WrapperWithDrop<()>)) -> [return: bb3, unwind: bb2];
}
}
```
In `bb4` and `bb5`, we assert that `(*_1).0` has type `WrapperWithDrop<()>`. However, In a user-facing param env, the type is actually `WrapperWithDrop<Tait>`. These types are not equal in a user-facing param-env (and can't be made equal even if we use `DefiningAnchor::Bubble`, since it's a non-local TAIT).
Warn on elided lifetimes in associated constants (`ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT`)
Elided lifetimes in associated constants (in impls) erroneously resolve to fresh lifetime parameters on the impl since #97313. This is not correct behavior (see #38831).
I originally opened #114716 to fix this, but given the time that has passed, the crater results seem pretty bad: https://github.com/rust-lang/rust/pull/114716#issuecomment-1682091952
This PR alternatively implements a lint against this behavior, and I'm hoping to bump this to deny in a few versions.
Add `suggestion` for some `#[deprecated]` items
Consider code:
```rust
fn main() {
let _ = ["a", "b"].connect(" ");
}
```
Currently it shows deprecated warning:
```rust
warning: use of deprecated method `std::slice::<impl [T]>::connect`: renamed to join
--> src/main.rs:2:24
|
2 | let _ = ["a", "b"].connect(" ");
| ^^^^^^^
|
= note: `#[warn(deprecated)]` on by default
```
This PR adds `suggestion` for `connect` and some other deprecated items, so the warning will be changed to this:
```rust
warning: use of deprecated method `std::slice::<impl [T]>::connect`: renamed to join
--> src/main.rs:2:24
|
2 | let _ = ["a", "b"].connect(" ");
| ^^^^^^^
|
= note: `#[warn(deprecated)]` on by default
help: replace the use of the deprecated method
|
2 | let _ = ["a", "b"].join(" ");
| ^^^^
```
Avoid side-effects from `try_coerce` when suggesting borrowing LHS of cast
The name `try_coerce` is a bit misleading -- it has side-effects, so when it's used in diagnostics code, it sometimes causes spurious obligations to be registered which cause other errors to occur that really make no sense in context.
Addendum: let's just rename `try_coerce` to `coerce` -- the `try_` part doesn't really add much, imo.
Normalize return type of `deduce_future_output_from_obligations`
Fixes#114909
Also confirmed to fix#114727 manually
Now that we have weak/lazy type aliases, we need to normalize those in future signatures to ensure that `replace_opaque_types_with_inference_vars` actually sees TAITs behind them. This isn't needed in the new solver, but added a test to make sure it doesn't regress there either.
r? types cc `@oli-obk` (who's gone, worst case can delay this PR until he's back)
Fix ABI flags in RISC-V/LoongArch ELF file generated by rustc
Fix#114153
It turns out the current way to set these flags are completely wrong. In LLVM the target ABI is used instead of target features to determine these flags.
Not sure how to write a test though. Or maybe a test isn't necessary because this affects only those touching target json?
r? `@Nilstrieb`
`Nonterminal`-related cleanups
In #114647 I am trying to remove `Nonterminal`. It has a number of preliminary cleanups that are worth merging even if #114647 doesn't merge, so let's do them in this PR.
r? `@petrochenkov`
[RFC-3086] Restrict the parsing of `count`
Fix#111904
The original RFC didn't mention the possibility of using `${count(t,)}` and such thing isn't very semantically accurate which can lead to confusion.
Normalize before checking if local is freeze in `deduced_param_attrs`
Not normalizing the local type eagerly results in possibly exponential amounts of normalization happening downstream in `is_freeze_raw`.
Fixes#113372
Revert PR #114052 to fix invalid suggestion
This PR reverts https://github.com/rust-lang/rust/pull/114052 to fix the invalid suggestion produced by the PR.
Unfortunately the invalid suggestion cannot be improved from the current position where it's emitted since we lack enough information (is an assignment?, left or right?, ...) to be able to fix it here. Furthermore the previous wasn't wrong, just suboptimal, contrary to the current one which is just wrong.
Added a regression test and commented out some code instead of removing it so we can use it later.
Reopens https://github.com/rust-lang/rust/issues/114050
Fixes https://github.com/rust-lang/rust/issues/114925
Fix suggestion for attempting to define a string with single quotes
Currently attempting to compile `fn main() { let _ = '\\"'; }` will result in the following error message:
```
error: character literal may only contain one codepoint
--> src/main.rs:1:21
|
1 | fn main() { let _ = '\\"'; }
| ^^^^^
|
help: if you meant to write a `str` literal, use double quotes
|
1 | fn main() { let _ = "\\""; }
| ~~~~~
```
The suggestion is invalid as it fails to escape the `"`. This PR fixes the suggestion so that it now reads:
```
help: if you meant to write a `str` literal, use double quotes
|
1 | fn main() { let _ = "\\\""; }
| ~~~~~~
```
The relevant test is also updated to ensure that this does not regress in future.
Fix argument removal suggestion around macros
Fixes#112437.
Fixes#113866.
Helps with #114255.
The issue was that `span.find_ancestor_inside(outer)` could previously return a span with a different expansion context from `outer`.
This happens for example for the built-in macro `panic!`, which expands to another macro call of `panic_2021!` or `panic_2015!`. Because the call site of `panic_20xx!` has not associated source code, its span currently points to the call site of `panic!` instead.
Something similar also happens items that get desugared in AST->HIR lowering. For example, `for` loops get two spans: One "inner" span that has the `.desugaring_kind()` kind set to `DesugaringKind::ForLoop` and one "outer" span that does not. Similar to the macro situation, both of these spans point to the same source code, but have different expansion contexts.
This causes problems, because joining two spans with different expansion contexts will usually[^1] not actually join them together to avoid creating "spaghetti" spans that go from the macro definition to the macro call. For example, in the following snippet `full_span` might not actually contain the `adjusted_start` and `adjusted_end`. This caused the broken suggestion / debug ICE in the linked issues.
```rust
let adjusted_start = start.find_ancestor_inside(shared_ancestor);
let adjusted_end = end.find_ancestor_inside(shared_ancestor);
let full_span = adjusted_start.to(adjusted_end)
```
To fix the issue, this PR introduces a new method, `find_ancestor_inside_same_ctxt`, which combines the functionality of `find_ancestor_inside` and `find_ancestor_in_same_ctxt`: It finds an ancestor span that is contained within the parent *and* has the same syntax context, and is therefore safe to extend. This new method should probably be used everywhere, where the returned span is extended, but for now it is just used for the argument removal suggestion.
Additionally, this PR fixes a second issue where the function call itself is inside a macro but the arguments come from outside the macro. The test is added in the first commit to include stderr diff, so this is best reviewed commit by commit.
[^1]: If one expansion context is the root context and the other is not.