Apply `EarlyOtherwiseBranch` to scalar value
In the future, I'm thinking of hoisting discriminant via GVN so that we only need to write very little code here.
r? `@cjgillot`
tests: Remove spuriously failing vec-tryinto-array codegen test
This has failed more than a couple of times now. It costs real time, money, and energy to deal with this, far more than this test is saving us.
Introduce `structurally_normalize_const`, use it in `rustc_hir_typeck`
Introduces `structurally_normalize_const` to typecking to separate the "eval a const" step from the "try to turn a valtree into a target usize" in HIR typeck, where we may still have infer vars and stuff around.
I also changed `check_expr_repeat` to move a double evaluation of a const into a single one. I'll leave inline comments.
r? ```@BoxyUwU```
I hesitated to really test this on the new solver where it probably matters for unevaluated consts. If you're worried about the side-effects, I'd be happy to craft some more tests 😄
Don't call `ty::Const::normalize` in error reporting
We do this to ensure that trait refs with unevaluated consts have those consts simplified to their evaluated forms. Instead, use `try_normalize_erasing_regions`.
**NOTE:** This has the side-effect of erasing regions from all of our trait refs. If this is too much to review or you think it's too opinionated of a diagnostics change, then I could split out the effective change (i.e. erasing regions from this impl suggestion) into another PR and have someone else review it.
No longer mark RTN as incomplete
The RFC is accepted and the feature is basically fully implemented. This doesn't mean it's necesarily *ready* for stabiliation; there's probably some diagnostic improvements to be made, and as always, users uncover the most creative bugs.
But marking this feature as incomplete no longer serves any purpose, so let's fix that.
Handle unsized consts with type `str` in v0 symbol mangling
This PR fixes#116303 by handling consts with type `str` in v0 symbol mangling as partial support for unsized consts.
This PR is related to `#![feature(adt_const_params)]` (#95174) and `#![feature(unsized_const_params)]` (#128028).
r? ``@BoxyUwU``
Add str.as_str() for easy Deref to string slices
Working with `Box<str>` is cumbersome, because in places like `iter.filter()` it can end up being `&Box<str>` or even `&&Box<str>`, and such type doesn't always get auto-dereferenced as expected.
Dereferencing such box to `&str` requires ugly syntax like `&**boxed_str` or `&***boxed_str`, with the exact amount of `*`s.
`Box<str>` is [not easily comparable with other string types](https://github.com/rust-lang/rust/pull/129852) via `PartialEq`. `Box<str>` won't work for lookups in types like `HashSet<String>`, because `Borrow<String>` won't take types like `&Box<str>`. OTOH `set.contains(s.as_str())` works nicely regardless of levels of indirection.
`String` has a simple solution for this: the `as_str()` method, and `Box<str>` should too.
It currently doesn't handle the three-char tokens `>>=` and `<<=`
correctly. These can be broken twice, resulting in three individual
tokens. This is a latent bug that currently doesn't cause any problems,
but does cause problems for #124141, because that PR increases the usage
of lazy token streams.
fix rustc_nonnull_optimization_guaranteed docs
As far as I can tell, even back when this was [added](https://github.com/rust-lang/rust/pull/60300) it never *enabled* any optimizations. It just indicates that the FFI compat lint should accept those types for NPO.
tests: Test that `extern "C" fn` ptrs lint on slices
This seems to have slipped past the `improper_ctypes_definitions` lint at some point. I found similar tests but not one with this exact combination, so test the semi-unique combination.
Prevent Deduplication of `LongRunningWarn`
Fixes#118612
As mention in the issue, `LongRunningWarn` is meant to be repeated multiple times.
Therefore, this PR stores a unique number in every instance of `LongRunningWarn` so that it's not hashed into the same value and omitted by the deduplication mechanism.
rustc_expand: remember module `#[path]`s during expansion
During invocation collection, if a module item parsed from a `#[path]` attribute needed a second pass after parsing, its path wouldn't get added to the file path stack, so cycle detection broke. This checks the `#[path]` in such cases, so that it gets added appropriately. I think it should work identically to the case for external modules that don't need a second pass, but I'm not 100% sure.
Fixes#97589
Fix anon const def-creation when macros are involved take 2
Fixes#130321
There were two cases that #129137 did not handle correctly:
- Given a const argument `Foo<{ bar!() }>` in which `bar!()` expands to `N`, we would visit the anon const and then visit the `{ bar() }` expression instead of visiting the macro call. This meant that we would build a def for the anon const as `{ bar!() }` is not a trivial const argument as `bar!()` is not a path.
- Given a const argument `Foo<{ bar!() }>` is which `bar!()` expands to `{ qux!() }` in which `qux!()` expands to `N`, it should not be considered a trivial const argument as `{{ N }}` has two pairs of braces. If we only looked at `qux`'s expansion it would *look* like a trivial const argument even though it is not. We have to track whether we have "unwrapped" a brace already when recursing into the expansions of `bar`/`qux`/any macro
r? `@camelid`
Assert that `explicit_super_predicates_of` and `explicit_item_super_predicates` truly only contains bounds for the type itself
We distinguish _implied_ predicates (anything that is implied from elaborating a trait bound) from _super_ predicates, which are are the subset of implied predicates that share the same self type as the trait predicate we're elaborating. This was originally done in #107614, which fixed a large class of ICEs and strange errors where the compiler expected the self type of a trait predicate not to change when elaborating super predicates.
Specifically, super predicates are special for various reasons: they're the valid candidates for trait upcasting, are the only predicates we elaborate when doing closure signature inference, etc. So making sure that we get this list correct and don't accidentally "leak" any other predicates into this list is quite important.
This PR adds some debug assertions that we're in fact not doing so, and it fixes an oversight in the effect desugaring rework.
Implement Return Type Notation (RTN)'s path form in where clauses
Implement return type notation (RTN) in path position for where clauses. We already had RTN in associated type position ([e.g.](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=627a4fb8e2cb334863fbd08ed3722c09)), but per [the RFC](https://rust-lang.github.io/rfcs/3654-return-type-notation.html#where-rtn-can-be-used-for-now):
> As a standalone type, RTN can only be used as the Self type of a where-clause [...]
Specifically, in order to enable code like:
```rust
trait Foo {
fn bar() -> impl Sized;
}
fn is_send(_: impl Send) {}
fn test<T>()
where
T: Foo,
T::bar(..): Send,
{
is_send(T::bar());
}
```
* In the resolver, when we see a `TyKind::Path` whose final segment is `GenericArgs::ParenthesizedElided` (i.e. `(..)`), resolve that path in the *value* namespace, since we're looking for a method.
* When lowering where clauses in HIR lowering, we first try to intercept an RTN self type via `lower_ty_maybe_return_type_notation`. If we find an RTN type, we lower it manually in a way that respects its higher-ranked-ness (see below) and resolves to the corresponding RPITIT. Anywhere else, we'll emit the same "return type notation not allowed in this position yet" error we do when writing RTN in every other position.
* In `resolve_bound_vars`, we add some special treatment for RTN types in where clauses. Specifically, we need to add new lifetime variables to our binders for the early- and late-bound vars we encounter on the method. This implements the higher-ranked desugaring [laid out in the RFC](https://rust-lang.github.io/rfcs/3654-return-type-notation.html#converting-to-higher-ranked-trait-bounds).
This PR also adds a bunch of tests, mostly negative ones (testing error messages).
In a follow-up PR, I'm going to mark RTN as no longer incomplete, since this PR basically finishes the impl surface that we should initially stabilize, and the RFC was accepted.
cc [RFC 3654](https://github.com/rust-lang/rfcs/pull/3654) and https://github.com/rust-lang/rust/issues/109417
add `extern "C-cmse-nonsecure-entry" fn`
tracking issue #75835
in https://github.com/rust-lang/rust/issues/75835#issuecomment-1183517255 it was decided that using an abi, rather than an attribute, was the right way to go for this feature.
This PR adds that ABI and removes the `#[cmse_nonsecure_entry]` attribute. All relevant tests have been updated, some are now obsolete and have been removed.
Error 0775 is no longer generated. It contains the list of targets that support the CMSE feature, and maybe we want to still use this? right now a generic "this abi is not supported on this platform" error is returned when this abi is used on an unsupported platform. On the other hand, users of this abi are likely to be experienced rust users, so maybe the generic error is good enough.
Correct outdated object size limit
The comment here about 48 bit addresses being enough was written in 2016 but was made incorrect in 2019 by 5-level paging, and then persisted for another 5 years before being noticed and corrected.
The bolding of the "exclusive" part is merely to call attention to something I missed when reading it and doublechecking the math.
try-job: i686-msvc
try-job: test-various
Don't alloca for unused locals
We already have a concept of mono-unreachable basic blocks; this is primarily useful for ensuring that we do not compile code under an `if false`. But since we never gave locals the same analysis, a large local only used under an `if false` will still have stack space allocated for it.
There are 3 places we traverse MIR during monomorphization: Inside the collector, `non_ssa_locals`, and the walk to generate code. Unfortunately, https://github.com/rust-lang/rust/pull/129283#issuecomment-2297925578 indicates that we cannot afford the expense of tracking reachable locals during the collector's traversal, so we do need at least two mono-reachable traversals. And of course caching is of no help here because the benchmarks that regress are incr-unchanged; they don't do any codegen.
This fixes the second problem in https://github.com/rust-lang/rust/issues/129282, and brings us anther step toward `const if` at home.
Explain why `non_snake_case` is skipped for binary crates and cleanup tests
- Explain `non_snake_case` lint is skipped for bin crate names because binaries are not intended to be distributed or consumed like library crates (#45127).
- Coalesce the bunch of tests into a single one but with revisions, which is easier to compare the differences for `non_snake_case` behavior with respect to crate types.
Follow-up to #121749 with some more comments and test cleanup.
cc `@saethlin` who bumped into one of the tests and was confused why it was `only-x86_64-unknown-linux-gnu`.
try-job: dist-i586-gnu-i586-i686-musl
Normalize consts in writeback when GCE is enabled
GCE lazily normalizes its unevaluated consts. This PR ensures that, like the new solver with its lazy norm types, we can assume that the writeback results are fully normalized.
This is important since we're trying to eliminate unnecessary calls to `ty::Const::{eval,normalize}` since they won't work with mGCE. Previously, we'd keep those consts unnormalized in writeback all the way through MIR build, and they'd only get normalized if we explicitly called `ty::Const::{eval,normalize}`, or during codegen since that calls `normalize_erasing_regions` (which invokes the `QueryNormalizer`, which evaluates the const accordingly).
This hack can (hopefully obviously) be removed when mGCE is implemented and we yeet the old GCE; it's only reachable with the GCE flag anyways, so I'm not worried about the implications here.
r? `@BoxyUwU`
Pass the current cargo to `run-make` tests
A couple tests were using `BOOTSTRAP_CARGO` with `-Zbuild-std`, but that
stage0 cargo might not always be in sync with in-tree changes. In
particular, those tests started failing on the beta branch because the
older cargo couldn't find the library `Cargo.lock`, and then couldn't
build the latest version of `compiler_builtins` that had nightly changes.
Fixes#130634
r? `@saethlin`
Add recursion limit to FFI safety lint
Fixes#130310
Now we check against `tcx.recursion_limit()` and raise an error if it the limit is reached instead of overflowing the stack.
A couple tests were using `BOOTSTRAP_CARGO` with `-Zbuild-std`, but that
stage0 cargo might not always be in sync with in-tree changes. In
particular, those tests started failing on the beta branch because the
older cargo couldn't find the library `Cargo.lock`, and then couldn't
build the latest version of `compiler_builtins` that had nightly changes.
bail if there are too many non-region infer vars in the query response
A minimal fix for the hang in nalgebra. If the query response would result in too many distinct non-region inference variables, simply overwrite the result with overflow. This should either happen if the result already has too many distinct type inference variables, or if evaluating the query encountered a lot of ambiguous associated types. In both cases it's straightforward to wait until the aliases are no longer ambiguous and then try again.
r? `@compiler-errors`
Add arm64e-apple-tvos target
This introduces
* `arm64e-apple-tvos`
## Tier 3 Target Policy
> * A tier 3 target must have a designated developer or developers (the "target
maintainers") on record to be CCed when issues arise regarding the target.
(The mechanism to track and CC such developers may evolve over time.)
I will be a target maintainer.
> * Targets must use naming consistent with any existing targets; for instance, a
target for the same CPU or OS as an existing Rust target should use the same
name for that CPU or OS. Targets should normally use the same names and
naming conventions as used elsewhere in the broader ecosystem beyond Rust
(such as in other toolchains), unless they have a very good reason to
diverge. Changing the name of a target can be highly disruptive, especially
once the target reaches a higher tier, so getting the name right is important
even for a tier 3 target.
Target names should not introduce undue confusion or ambiguity unless
absolutely necessary to maintain ecosystem compatibility. For example, if
the name of the target makes people extremely likely to form incorrect
beliefs about what it targets, the name should be changed or augmented to
disambiguate it.
If possible, use only letters, numbers, dashes and underscores for the name.
Periods (.) are known to cause issues in Cargo.
The `arm64e-apple-tvos` target names like `arm64e-apple-ios`, `arm64e-apple-darwin`.
So, **I have chosen this name because there are similar triplets in LLVM**. I think there are no more suitable names for these targets.
> * Tier 3 targets may have unusual requirements to build or use, but must not
create legal issues or impose onerous legal terms for the Rust project or for
Rust developers or users.
The target must not introduce license incompatibilities.
Anything added to the Rust repository must be under the standard Rust
license (MIT OR Apache-2.0).
The target must not cause the Rust tools or libraries built for any other
host (even when supporting cross-compilation to the target) to depend
on any new dependency less permissive than the Rust licensing policy. This
applies whether the dependency is a Rust crate that would require adding
new license exceptions (as specified by the tidy tool in the
rust-lang/rust repository), or whether the dependency is a native library
or binary. In other words, the introduction of the target must not cause a
user installing or running a version of Rust or the Rust tools to be
subject to any new license requirements.
Compiling, linking, and emitting functional binaries, libraries, or other
code for the target (whether hosted on the target itself or cross-compiling
from another target) must not depend on proprietary (non-FOSS) libraries.
Host tools built for the target itself may depend on the ordinary runtime
libraries supplied by the platform and commonly used by other applications
built for the target, but those libraries must not be required for code
generation for the target; cross-compilation to the target must not require
such libraries at all. For instance, rustc built for the target may
depend on a common proprietary C runtime library or console output library,
but must not depend on a proprietary code generation library or code
optimization library. Rust's license permits such combinations, but the
Rust project has no interest in maintaining such combinations within the
scope of Rust itself, even at tier 3.
"onerous" here is an intentionally subjective term. At a minimum, "onerous"
legal/licensing terms include but are not limited to: non-disclosure
requirements, non-compete requirements, contributor license agreements
(CLAs) or equivalent, "non-commercial"/"research-only"/etc terms,
requirements conditional on the employer or employment of any particular
Rust developers, revocable terms, any requirements that create liability
for the Rust project or its developers or users, or any requirements that
adversely affect the livelihood or prospects of the Rust project or its
developers or users.
No dependencies were added to Rust.
> * Neither this policy nor any decisions made regarding targets shall create any
binding agreement or estoppel by any party. If any member of an approving
Rust team serves as one of the maintainers of a target, or has any legal or
employment requirement (explicit or implicit) that might affect their
decisions regarding a target, they must recuse themselves from any approval
decisions regarding the target's tier status, though they may otherwise
participate in discussions.
> * This requirement does not prevent part or all of this policy from being
cited in an explicit contract or work agreement (e.g. to implement or
maintain support for a target). This requirement exists to ensure that a
developer or team responsible for reviewing and approving a target does not
face any legal threats or obligations that would prevent them from freely
exercising their judgment in such approval, even if such judgment involves
subjective matters or goes beyond the letter of these requirements.
Understood.
I am not a member of a Rust team.
> * Tier 3 targets should attempt to implement as much of the standard libraries
as possible and appropriate (core for most targets, alloc for targets
that can support dynamic memory allocation, std for targets with an
operating system or equivalent layer of system-provided functionality), but
may leave some code unimplemented (either unavailable or stubbed out as
appropriate), whether because the target makes it impossible to implement or
challenging to implement. The authors of pull requests are not obligated to
avoid calling any portions of the standard library on the basis of a tier 3
target not implementing those portions.
Understood.
`std` is supported.
> * The target must provide documentation for the Rust community explaining how
to build for the target, using cross-compilation if possible. If the target
supports running binaries, or running tests (even if they do not pass), the
documentation must explain how to run such binaries or tests for the target,
using emulation if possible or dedicated hardware if necessary.
Building is described in the derived target doc.
> * Tier 3 targets must not impose burden on the authors of pull requests, or
other developers in the community, to maintain the target. In particular,
do not post comments (automated or manual) on a PR that derail or suggest a
block on the PR based on a tier 3 target. Do not send automated messages or
notifications (via any medium, including via `@)` to a PR author or others
involved with a PR regarding a tier 3 target, unless they have opted into
such messages.
> * Backlinks such as those generated by the issue/PR tracker when linking to
an issue or PR are not considered a violation of this policy, within
reason. However, such messages (even on a separate repository) must not
generate notifications to anyone involved with a PR who has not requested
such notifications.
Understood.
> * Patches adding or updating tier 3 targets must not break any existing tier 2
or tier 1 target, and must not knowingly break another tier 3 target without
approval of either the compiler team or the maintainers of the other tier 3
target.
> * In particular, this may come up when working on closely related targets,
such as variations of the same architecture with different features. Avoid
introducing unconditional uses of features that another variation of the
target may not have; use conditional compilation or runtime detection, as
appropriate, to let each target run code supported by that target.
Understood.
https://github.com/rust-lang/rust/issues/121663https://github.com/rust-lang/rust/issues/73628
Begin experimental support for pin reborrowing
This commit adds basic support for reborrowing `Pin` types in argument position. At the moment it only supports reborrowing `Pin<&mut T>` as `Pin<&mut T>` by inserting a call to `Pin::as_mut()`, and only in argument position (not as the receiver in a method call).
This PR makes the following example compile:
```rust
#![feature(pin_ergonomics)]
fn foo(_: Pin<&mut Foo>) {
}
fn bar(mut x: Pin<&mut Foo>) {
foo(x);
foo(x);
}
```
Previously, you would have had to write `bar` as:
```rust
fn bar(mut x: Pin<&mut Foo>) {
foo(x.as_mut());
foo(x);
}
```
Tracking:
- #130494
r? `@compiler-errors`
Remove macOS 10.10 dynamic linker bug workaround
Rust's current minimum macOS version is 10.12, so the hack can be removed. This PR also updates the `remove_dir_all` docs to reflect that all supported macOS versions are protected against TOCTOU race conditions (the fallback implementation was already removed in #127683).
try-job: dist-x86_64-apple
try-job: dist-aarch64-apple
try-job: dist-apple-various
try-job: aarch64-apple
try-job: x86_64-apple-1
The issue-112505-overflow test just extended a case of transmute-fail.rs
so simply put them in the same file.
Then we normalize away other cases of this.
Fix feature name in test
This is meant to test that the `box_patterns` feature isn't active due to the `cfg(FALSE)`, but uses the removed `box_syntax` feature. Fix this so it's testing what it should be.
Get rid of niche selection's dependence on fields's order
Fixes#125630.
Use the optimal niche selection decided in `univariant()` rather than picking niche field manually.
r? `@the8472`
Generating a call to `as_mut()` let to more restrictive borrows than
what reborrowing usually gives us. Instead, we change the desugaring to
reborrow the pin internals directly which makes things more expressive.
Never patterns constitute a read for unsafety
This code is otherwise unsound if we don't emit an unsafety error here. Noticed when fixing #130528, but it's totally unrelated.
r? `@Nadrieril`
Check params for unsafety in THIR
Self-explanatory. I'm not surprised this was overlooked, given the way that THIR visitors work. Perhaps we should provide a better entrypoint.
Fixes#130528
Further improve diagnostics for expressions in pattern position
Follow-up of #118625, see #121697.
```rs
fn main() {
match 'b' {
y.0.0.1.z().f()? as u32 => {},
}
}
```
Before:
```
error: expected one of `=>`, ``@`,` `if`, or `|`, found `.`
--> src/main.rs:3:10
|
3 | y.0.0.1.z().f()? as u32 => {},
| ^ expected one of `=>`, ``@`,` `if`, or `|`
```
After:
```
error: expected a pattern, found an expression
--> src/main.rs:3:9
|
3 | y.0.0.1.z().f()? as u32 => {},
| ^^^^^^^^^^^^^^^^^^^^^^^ arbitrary expressions are not allowed in patterns
|
help: consider moving the expression to a match arm guard
|
3 | val if val == y.0.0.1.z().f()? as u32 => {},
| ~~~ +++++++++++++++++++++++++++++++++
help: consider extracting the expression into a `const`
|
2 + const VAL: /* Type */ = y.0.0.1.z().f()? as u32;
3 ~ match 'b' {
4 ~ VAL => {},
|
help: consider wrapping the expression in an inline `const` (requires `#![feature(inline_const_pat)]`)
|
3 | const { y.0.0.1.z().f()? as u32 } => {},
| +++++++ +
```
---
r? fmease
`@rustbot` label +A-diagnostics +A-parser +A-patterns +C-enhancement
Update the minimum external LLVM to 18
With this change, we'll have stable support for LLVM 18 and 19.
For reference, the previous increase to LLVM 17 was #122649.
cc `@rust-lang/wg-llvm`
r? nikic
Reduce confusion about `make_indirect_byval` by renaming it
As part of doing so, remove the incorrect handling of the wasm target's `make_indirect_byval` (i.e. using it at all).
Gate `repr(Rust)` correctly on non-ADT items
#114201 added `repr(Rust)` but didn't add any attribute validation to it like `repr(C)` has, to only allow it on ADT items.
I consider this code to be nonsense, for example:
```
#[repr(Rust)]
fn foo() {}
```
Reminder that it's different from `extern "Rust"`, which *is* valid on function items. But also this now disallows `repr(Rust)` on modules, impls, traits, etc.
I'll crater it, if it looks bad then I'll add an FCW.
---
https://github.com/rust-lang/rust/labels/relnotes: Compatibility (minor breaking change).
Do not ICE with incorrect empty suggestion
When we have two types with the same name, one without type parameters and the other with type parameters and a derive macro, we were before incorrectly suggesting to remove type parameters from the former, which ICEd because we were suggesting to remove nothing. We now gate against this.
The output is still not perfect. E0107 should explicitly detect this case and provide better context, but for now let's avoid the ICE.
Fix#108748.
This commit adds basic support for reborrowing `Pin` types in argument
position. At the moment it only supports reborrowing `Pin<&mut T>` as
`Pin<&mut T>` by inserting a call to `Pin::as_mut()`, and only in
argument position (not as the receiver in a method call).
When we have two types with the same name, one without type parameters and the other with type parameters and a derive macro, we were before incorrectly suggesting to remove type parameters from the former, which ICEd because we were suggesting to remove nothing. We now gate against this.
The output is still not perfect. E0107 should explicitly detect this case and provide better context, but for now let's avoid the ICE.
Improve handling of raw-idents in check-cfg
This PR improves the handling of raw-idents in the check-cfg diagnostics.
In particular the list of expected names and the suggestion now correctly take into account the "keyword-ness" of the ident, and correctly prefix the ident with `r#` when necessary.
`@rustbot` labels +F-check-cfg
Rollup of 3 pull requests
Successful merges:
- #130466 (tests: add repr/transparent test for aarch64)
- #130468 (Make sure that def id <=> lang item map is bidirectional)
- #130499 (Add myself to the libs review rotation)
r? `@ghost`
`@rustbot` modify labels: rollup
tests: add repr/transparent test for aarch64
Fixes#74396.
Moves `transparent-struct-ptr.rs` to `transparent-byval-struct-ptr.rs` and then adds a new `transparent-opaque-ptr.rs` for aarch64.
Fix circular fn_sig queries to correct number of args for methods
Fixes#130400. This was a [debug assert](28e8f01c2a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs (L2557)) added to some argument error reporting code in #129320 which verified that the number of params (from the HIR) matched the `matched_inputs` which ultimately come from ty::FnSig. In the reduced test case:
```
fn foo(&mut self) -> _ {
foo()
}
```
There is a circular dependency computing the ty::FnSig -- when trying to compute it, we try to figure out the return value, which again depends on this ty::FnSig. In #105162, this was supported by short-circuiting the cycle by synthesizing a FnSig with error types for parameters. The [code in question](https://github.com/rust-lang/rust/pull/105162/files#diff-a65feec6bfffb19fbdc60a80becd1030c82a56c16b177182cd277478fdb04592R44) computes the number of parameters by taking the number of parameters from the hir::FnDecl and adding 1 if there is an implicit self parameter.
I might be missing a subtlety here, but AFAICT the adjustment for implicit self args is unnecessary and results in one too many args. For example, for this non-errorful code:
```
trait Foo {
fn bar(&self) {}
}
```
The resulting hir::FnDecl and ty::FnSig both have the same number of inputs -- 1. So, this PR removes that adjustment and adds a test for the debug ICE.
r? `@compiler-errors`
Implement a Method to Seal `DiagInner`'s Suggestions
This PR adds a method on `DiagInner` called `.seal_suggestions()` to prevent new suggestions from being added while preserving existing suggestions.
This is useful because currently there is no way to prevent new suggestions from being added to a diagnostic. `.disable_suggestions()` is the closest but it gets rid of all suggestions before and after the call.
Therefore, `.seal_suggestions()` can be used when, for example, misspelled keyword is detected and reported. In such cases, we may want to prevent other suggestions from being added to the diagnostic, as they would likely be meaningless once the misspelled keyword is identified. For context: https://github.com/rust-lang/rust/pull/129899#discussion_r1741307132
To store an additional state, the type of the `suggestions` field in `DiagInner` was changed into a three variant enum. While this change affects files across different crates, care was taken to preserve the existing code's semantics. This is validated by the fact that all UI tests pass without any modifications.
r? chenyukang
tests: allow trunc/select instructions to be missing
On LLVM 20, these instructions already get eliminated, which at least partially satisfies a TODO. I'm not talented enough at using FileCheck to try and constrain this further, but if we really want to we could copy an LLVM 20 specific version of this test that would restore it to being CHECK-NEXT: insertvalue ...
`@rustbot` label: +llvm-main
r? `@DianQK`
Currently constants are "pulled forward" and have their stack spills emitted
first. This confuses LLVM as to where to place breakpoints at function
entry, and results in argument values being wrong in the debugger. It's
straightforward to avoid emitting the stack spills for constants until
arguments/etc have been introduced in debug_introduce_locals, so do that.
Example LLVM IR (irrelevant IR elided):
Before:
define internal void @_ZN11rust_1289457binding17h2c78f956ba4bd2c3E(i64 %a, i64 %b, double %c) unnamed_addr #0 !dbg !178 {
start:
%c.dbg.spill = alloca [8 x i8], align 8
%b.dbg.spill = alloca [8 x i8], align 8
%a.dbg.spill = alloca [8 x i8], align 8
%x.dbg.spill = alloca [4 x i8], align 4
store i32 0, ptr %x.dbg.spill, align 4, !dbg !192 ; LLVM places breakpoint here.
#dbg_declare(ptr %x.dbg.spill, !190, !DIExpression(), !192)
store i64 %a, ptr %a.dbg.spill, align 8
#dbg_declare(ptr %a.dbg.spill, !187, !DIExpression(), !193)
store i64 %b, ptr %b.dbg.spill, align 8
#dbg_declare(ptr %b.dbg.spill, !188, !DIExpression(), !194)
store double %c, ptr %c.dbg.spill, align 8
#dbg_declare(ptr %c.dbg.spill, !189, !DIExpression(), !195)
ret void, !dbg !196
}
After:
define internal void @_ZN11rust_1289457binding17h2c78f956ba4bd2c3E(i64 %a, i64 %b, double %c) unnamed_addr #0 !dbg !178 {
start:
%x.dbg.spill = alloca [4 x i8], align 4
%c.dbg.spill = alloca [8 x i8], align 8
%b.dbg.spill = alloca [8 x i8], align 8
%a.dbg.spill = alloca [8 x i8], align 8
store i64 %a, ptr %a.dbg.spill, align 8
#dbg_declare(ptr %a.dbg.spill, !187, !DIExpression(), !192)
store i64 %b, ptr %b.dbg.spill, align 8
#dbg_declare(ptr %b.dbg.spill, !188, !DIExpression(), !193)
store double %c, ptr %c.dbg.spill, align 8
#dbg_declare(ptr %c.dbg.spill, !189, !DIExpression(), !194)
store i32 0, ptr %x.dbg.spill, align 4, !dbg !195 ; LLVM places breakpoint here.
#dbg_declare(ptr %x.dbg.spill, !190, !DIExpression(), !195)
ret void, !dbg !196
}
Note in particular the position of the "LLVM places breakpoint here" comment
relative to the stack spills for the function arguments. LLVM assumes that
the first instruction with with a debug location is the end of the prologue.
As LLVM does not currently offer front ends any direct control over the
placement of the prologue end reordering the IR is the only mechanism available
to fix argument values at function entry in the presence of MIR optimizations
like SingleUseConsts. Fixes#128945
Remove redundant test typeid equality by subtyping
This known-bug label was a left over on #118247
r? `@jackh726`
This doesn't address #110395, I didn't investigate about it yet.
In 2021 pat was changed to recognize `|` at the top level, with
pat_param added to retain the old behavior. This means
pat is subject to the same cross-edition behavior as expr will be in
2024.
Co-authored-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
There's a subtle interaction between macros with metavar expressions and the
edition-dependent fragment matching behavior. This test illustrates the current
behavior when using macro-generating-macros across crate boundaries with
different editions.
Co-Authored-By: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
Co-Authored-By: Eric Holk <eric@theincredibleholk.org>
Don't call `extern_crate` when local crate name is the same as a dependency and we have a trait error
#124944 implemented logic to point out when a trait bound failure involves a *trait* and *type* who come from identically named but different crates. This logic calls the `extern_crate` query which is not valid on `LOCAL_CRATE` cnum, so let's filter that out eagerly.
Fixes#130272Fixes#129184
Encode `coroutine_by_move_body_def_id` in crate metadata
We synthesize the MIR for a by-move body for the `FnOnce` implementation of async closures. It can be accessed with the `coroutine_by_move_body_def_id` query. We weren't encoding this query in the metadata though, nor were we properly recording that synthetic MIR in `mir_keys`, so the `optimized_mir` wasn't getting encoded either!
Stacked on top is a fix to consider `DefKind::SyntheticCoroutineBody` to return true in several places I missed. Specifically, we should consider the def-kind in `fn DefKind::is_fn_like()`, since that's what we were using to make sure we ensure `query mir_inliner_callees` before the MIR gets stolen for the body. This led to some CI failures that were caught by miri but which I added a test for.
Use `Vec` in `rustc_interface::Config::locale_resources`
This allows a third-party tool to injects its own resources, when receiving the config via `rustc_driver::Callbacks::config`.
Fix#128930: Print documentation of CLI options missing their arg
Fix#128930. Failing to give an argument to CLI options which require it now prints something like:
```
$ rustc --print
error: Argument to option 'print' missing
Usage:
--print [crate-name|file-names|sysroot|target-libdir|cfg|check-cfg|calling-conventions|target-list|target-cpus|target-features|relocation-models|code-models|tls-models|target-spec-json|all-target-specs-json|native-static-libs|stack-protector-strategies|link-args|deployment-target]
Compiler information to print on stdout
```
On LLVM 20, these instructions already get eliminated, which at least
partially satisfies a TODO. I'm not talented enough at using FileCheck
to try and constrain this further, but if we really want to we could
copy an LLVM 20 specific version of this test that would restore it to
being CHECK-NEXT: insertvalue ...
@rustbot label: +llvm-main
Relate receiver invariantly in method probe for `Mode::Path`
Effectively reverts part of #126128Fixes#126227
This PR changes method probing to use equality for fully path-based method lookup, and subtyping for receiver `.` method lookup.
r? lcnr
Remove semi-nondeterminism of `DefPathHash` ordering from inliner
Déjà vu or something because I kinda thought I had put this PR up before. I recall a discussion somewhere where I think it was `@saethlin` mentioning that this check was no longer needed since we have "proper" cycle detection. Putting that up as a PR now.
This may slighlty negatively affect inlining, since the cycle breaking here means that we still inlined some cycles when the def path hashes were ordered in certain ways, this leads to really bad nondeterminism that makes minimizing ICEs and putting up inliner bugfixes difficult.
r? `@cjgillot` or `@saethlin` or someone else idk
run_make_support: rectify symlink handling
Avoid confusing Unix symlinks and Windows symlinks. Since their
semantics are quite different, we should avoid trying to make it
automagic in how symlinks are created and deleted. Notably, the tests
should reflect what type of symlinks are to be created to match what std
does to make it less surprising for test readers.
layout computation: gracefully handle unsized types in unexpected locations
This PR reworks the layout computation to eagerly return an error when encountering an unsized field where a sized field was expected, rather than delaying a bug and attempting to recover a layout. This is required, because with trivially false where clauses like `[T]: Sized`, any field can possible be an unsized type, without causing a compile error.
Since this PR removes the `delayed_bug` method from the `LayoutCalculator` trait, it essentially becomes the same as the `HasDataLayout` trait, so I've also refactored the `LayoutCalculator` to be a simple wrapper struct around a type that implements `HasDataLayout`.
The majority of the diff is whitespace changes, so viewing with whitespace ignored is advised.
implements https://github.com/rust-lang/rust/pull/123169#issuecomment-2025788480
r? `@compiler-errors` or compiler
fixes https://github.com/rust-lang/rust/issues/123134
fixes https://github.com/rust-lang/rust/issues/124182
fixes https://github.com/rust-lang/rust/issues/126939
fixes https://github.com/rust-lang/rust/issues/127737
For structs that cannot be unsized, the layout algorithm sometimes moves
unsized fields to the end of the struct, which circumvented the error
for unexpected unsized fields and returned an unsized layout anyway.
This commit makes it so that the unexpected unsized error is always
returned for structs that cannot be unsized, allowing us to remove an
old hack and fixing some old ICE.
Rollup of 3 pull requests
Successful merges:
- #130033 (Don't call `fn_arg_names` query for non-`fn` foreign items in resolver)
- #130282 (Do not report an excessive number of overflow errors for an ever-growing deref impl)
- #130437 (Avoid crashing on variadic functions when producing arg-mismatch errors)
r? `@ghost`
`@rustbot` modify labels: rollup
Avoid crashing on variadic functions when producing arg-mismatch errors
Fixes#130372 by accommodating how variadic functions change the argument list length between HIR body and FnDecls.
Also degrades the zip_eq to a debug_assert! to match other asserts in the area to avoid being disruptive to users. There is at least one other crash in this area I am working on in #130400 and also considering how we might refactor some of this code to hoist some of this logic up higher.
r? `@compiler-errors`
Do not report an excessive number of overflow errors for an ever-growing deref impl
Check that we don't first hit the recursion limit in `get_field_candidates_considering_privacy` before probing for methods when we have a method lookup failure and we want to see if `.field.method()` exists. We also silence overflow error messages if we're probing for methods for diagnostics.
Also renames some functions to make it clearer that they're only for diagnostics, and sprinkle some `Autoderef::silence_errors` around to silence unnecessary overflow errors that come from diagnostics.
Fixes#130224.
Rollup of 4 pull requests
Successful merges:
- #123436 (linker: Allow MSVC to use import libraries following the Meson/MinGW convention)
- #130410 (Don't ICE when generating `Fn` shim for async closure with borrowck error)
- #130412 (Don't ICE when RPITIT captures more method args than trait definition)
- #130436 (Ignore reduce-fadd-unordered on SGX platform)
r? `@ghost`
`@rustbot` modify labels: rollup
Ignore reduce-fadd-unordered on SGX platform
#130325 added the `tests/assembly/simd/reduce-fadd-unordered.rs` test. Unfortunately, the use of `CHECK: ret` makes that this test is not compatible with LVI mitigations applied for the SGX target. This PR makes sure this test is ignored for the SGX target, until a nicer solution is available.
Don't ICE when RPITIT captures more method args than trait definition
Make sure we don't ICE when an RPITIT captures more method args than the trait definition, which is not allowed. This was because we were using the wrong def id for error reporting.
Due to the default lifetime capture rules of RPITITs (capturing everything in scope), this is only doable if we use precise capturing, which isn't currently allowed for RPITITs anyways but we still end up reaching the relevant codepaths.
Fixes#129850
Don't use `typeck_root_def_id` in codegen for finding closure's root
Generating debuginfo in codegen currently peels off all the closure-specific generics (which presumably is done because they're redundant). This doesn't currently work correctly for the bodies we synthesize for async closures's returned coroutines (#128506), leading to #129702.
Specifically, `typeck_root_def_id` for some `DefKind::SyntheticCoroutineBody` just returns itself (because it loops while `is_typeck_child` is `true`, and that returns `false` for this defkind), which means we don't end up peeling off the coroutine-specific generics, and we end up encountering an otherwise unreachable `CoroutineWitness` type leading to an ICE.
This PR fixes `is_typeck_child` to consider `DefKind::SyntheticCorotuineBody` to be a typeck child, fixing `typeck_root_def_id` and suppressing this debuginfo bug.
Fixes#129702
Use -0.0 in `intrinsics::simd::reduce_add_unordered`
-0.0 is the actual neutral additive float, not +0.0, and this matters to codegen.
try-job: aarch64-gnu
simplify float::classify logic
I played around with the float-classify test in the hope of triggering x87 bugs by strategically adding `black_box`, and still the exact expression `@beetrees` suggested [here](https://github.com/rust-lang/rust/pull/129835#issuecomment-2325661597) remains the only case I found where we get the wrong result on x87. Curiously, this bug only occurs when MIR optimizations are enabled -- probably the extra inlining that does is required for LLVM to hit the right "bad" case in the backend. But even for that case, it makes no difference whether `classify` is implemented in the simple bit-pattern-based version or the more complicated version we had before.
Without even a single testcase that can distinguish our `classify` from the naive version, I suggest we switch to the naive version.
interpret, miri: fix dealing with overflow during slice indexing and allocation
This is mostly to fix https://github.com/rust-lang/rust/issues/130284.
I then realized we're using somewhat sketchy arguments for a similar multiplication in `copy`/`copy_nonoverlapping`/`write_bytes`, so I made them all share the same function that checks exactly the right thing. (The intrinsics would previously fail on allocations larger than `1 << 47` bytes... which are theoretically possible maybe? Anyway it seems conceptually wrong to use any other bound than `isize::MAX` here.)
Correctly account for niche-optimized tags in rustc_transmute
This is a bit hacky, but it fixes the ICE and makes it possible to run the safe transmute check on every `mem::transmute` check we instantiate. I want to write a lint that needs to do that, but this stands well on its own.
cc `@jswrenn` here's the fix I alluded to yesterday :)
Fixes#123693
Stabilize `&mut` (and `*mut`) as well as `&Cell` (and `*const Cell`) in const
This stabilizes `const_mut_refs` and `const_refs_to_cell`. That allows a bunch of new things in const contexts:
- Mentioning `&mut` types
- Creating `&mut` and `*mut` values
- Creating `&T` and `*const T` values where `T` contains interior mutability
- Dereferencing `&mut` and `*mut` values (both for reads and writes)
The same rules as at runtime apply: mutating immutable data is UB. This includes mutation through pointers derived from shared references; the following is diagnosed with a hard error:
```rust
#[allow(invalid_reference_casting)]
const _: () = {
let mut val = 15;
let ptr = &val as *const i32 as *mut i32;
unsafe { *ptr = 16; }
};
```
The main limitation that is enforced is that the final value of a const (or non-`mut` static) may not contain `&mut` values nor interior mutable `&` values. This is necessary because the memory those references point to becomes *read-only* when the constant is done computing, so (interior) mutable references to such memory would be pretty dangerous. We take a multi-layered approach here to ensuring no mutable references escape the initializer expression:
- A static analysis rejects (interior) mutable references when the referee looks like it may outlive the current MIR body.
- To be extra sure, this static check is complemented by a "safety net" of dynamic checks. ("Dynamic" in the sense of "running during/after const-evaluation, e.g. at runtime of this code" -- in contrast to "static" which works entirely by looking at the MIR without evaluating it.)
- After the final value is computed, we do a type-driven traversal of the entire value, and if we find any `&mut` or interior-mutable `&` we error out.
- However, the type-driven traversal cannot traverse `union` or raw pointers, so there is a second dynamic check where if the final value of the const contains any pointer that was not derived from a shared reference, we complain. This is currently a future-compat lint, but will become an ICE in #128543. On the off-chance that it's actually possible to trigger this lint on stable, I'd prefer if we could make it an ICE before stabilizing const_mut_refs, but it's not a hard blocker. This part of the "safety net" is only active for mutable references since with shared references, it has false positives.
Altogether this should prevent people from leaking (interior) mutable references out of the const initializer.
While updating the tests I learned that surprisingly, this code gets rejected:
```rust
const _: Vec<i32> = {
let mut x = Vec::<i32>::new(); //~ ERROR destructor of `Vec<i32>` cannot be evaluated at compile-time
let r = &mut x;
let y = x;
y
};
```
The analysis that rejects destructors in `const` is very conservative when it sees an `&mut` being created to `x`, and then considers `x` to be always live. See [here](https://github.com/rust-lang/rust/issues/65394#issuecomment-541499219) for a longer explanation. `const_precise_live_drops` will solve this, so I consider this problem to be tracked by https://github.com/rust-lang/rust/issues/73255.
Cc `@rust-lang/wg-const-eval` `@rust-lang/lang`
Cc https://github.com/rust-lang/rust/issues/57349
Cc https://github.com/rust-lang/rust/issues/80384
Add `NonNull` convenience methods to `Box` and `Vec`
Implements the ACP: https://github.com/rust-lang/libs-team/issues/418.
The docs for the added methods are mostly copied from the existing methods that use raw pointers instead of `NonNull`.
I'm new to this "contributing to rustc" thing, so I'm sorry if I did something wrong. In particular, I don't know what the process is for creating a new unstable feature. Please advise me if I should do something. Thank you.
stabilize `const_extern_fn`
closes https://github.com/rust-lang/rust/issues/64926
tracking issue: https://github.com/rust-lang/rust/issues/64926
reference PR: https://github.com/rust-lang/reference/pull/1596
## Stabilizaton Report
### Summary
Using `const extern "Rust"` and `const extern "C"` was already stabilized (since version 1.62.0, see https://github.com/rust-lang/rust/pull/95346). This PR stabilizes the other calling conventions: it is now possible to write `const unsafe extern "calling-convention" fn` and `const extern "calling-convention" fn` for any supported calling convention:
```rust
const extern "C-unwind" fn foo1(val: u8) -> u8 { val + 1}
const extern "stdcall" fn foo2(val: u8) -> u8 { val + 1}
const unsafe extern "C-unwind" fn bar1(val: bool) -> bool { !val }
const unsafe extern "stdcall" fn bar2(val: bool) -> bool { !val }
```
This can be used to const-ify an `extern fn`, or conversely, to make a `const fn` callable from external code.
r? T-lang
cc `@RalfJung`
const-eval interning: accept interior mutable pointers in final value
…but keep rejecting mutable references
This fixes https://github.com/rust-lang/rust/issues/121610 by no longer firing the lint when there is a pointer with interior mutability in the final value of the constant. On stable, such pointers can be created with code like:
```rust
pub enum JsValue {
Undefined,
Object(Cell<bool>),
}
impl Drop for JsValue {
fn drop(&mut self) {}
}
// This does *not* get promoted since `JsValue` has a destructor.
// However, the outer scope rule applies, still giving this 'static lifetime.
const UNDEFINED: &JsValue = &JsValue::Undefined;
```
It's not great to accept such values since people *might* think that it is legal to mutate them with unsafe code. (This is related to how "infectious" `UnsafeCell` is, which is a [wide open question](https://github.com/rust-lang/unsafe-code-guidelines/issues/236).) However, we [explicitly document](https://doc.rust-lang.org/reference/behavior-considered-undefined.html) that things created by `const` are immutable. Furthermore, we also accept the following even more questionable code without any lint today:
```rust
let x: &'static Option<Cell<i32>> = &None;
```
This is even more questionable since it does *not* involve a `const`, and yet still puts the data into immutable memory. We could view this as promotion [potentially introducing UB](https://github.com/rust-lang/unsafe-code-guidelines/issues/493). However, we've accepted this since ~forever and it's [too late to reject this now](https://github.com/rust-lang/rust/pull/122789); the pattern is just too useful.
So basically, if you think that `UnsafeCell` should be tracked fully precisely, then you should want the lint we currently emit to be removed, which this PR does. If you think `UnsafeCell` should "infect" surrounding `enum`s, the big problem is really https://github.com/rust-lang/unsafe-code-guidelines/issues/493 which does not trigger the lint -- the cases the lint triggers on are actually the "harmless" ones as there is an explicit surrounding `const` explaining why things end up being immutable.
What all this goes to show is that the hard error added in https://github.com/rust-lang/rust/pull/118324 (later turned into the future-compat lint that I am now suggesting we remove) was based on some wrong assumptions, at least insofar as it concerns shared references. Furthermore, that lint does not help at all for the most problematic case here where the potential UB is completely implicit. (In fact, the lint is actively in the way of [my preferred long-term strategy](https://github.com/rust-lang/unsafe-code-guidelines/issues/493#issuecomment-2028674105) for dealing with this UB.) So I think we should go back to square one and remove that error/lint for shared references. For mutable references, it does seem to work as intended, so we can keep it. Here it serves as a safety net in case the static checks that try to contain mutable references to the inside of a const initializer are not working as intended; I therefore made the check ICE to encourage users to tell us if that safety net is triggered.
Closes https://github.com/rust-lang/rust/issues/122153 by removing the lint.
Cc `@rust-lang/opsem` `@rust-lang/lang`
Fix `Parser::break_up_float`'s right span
```rs
use std::mem::offset_of;
fn main() {
offset_of!((u8,), 0.0);
}
```
Before:
```
error[E0609]: no field `0` on type `u8`
--> ./main.rs:4:25
|
4 | offset_of!((u8,), 0.0);
| _____--------------------^-
| | |
| | in this macro invocation
5 | | }
... |
|
= note: this error originates in the macro `offset_of` (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to 1 previous error
```
After:
```
error[E0609]: no field `0` on type `u8`
--> ./main.rs:4:25
|
4 | offset_of!((u8,), 0.0);
| ^
error: aborting due to 1 previous error
```
---
`@rustbot` label +A-parser +D-imprecise-spans
simd_shuffle: require index argument to be a vector
Remove some codegen hacks by forcing the SIMD shuffle `index` argument to be a vector, which means (thanks to https://github.com/rust-lang/rust/pull/128537) that it will automatically be passed as an immediate in LLVM. The only special-casing we still have is for the extra sanity-checks we add that ensure that the indices are all in-bounds. (And the GCC backend needs to do a bunch of work since the Rust intrinsic is modeled after what LLVM expects, which seems to be quite different from what GCC expects.)
Fixes https://github.com/rust-lang/rust/issues/128738, see that issue for more context.
coverage: Extract `executor::block_on` from several async coverage tests
By moving `block_on` to an auxiliary crate, we avoid having to keep a separate copy of it in every async test.
Simplify the canonical clone method and the copy-like forms to copy
Fixes#128081.
The optimized clone method ends up as the following MIR:
```
_2 = copy ((*_1).0: i32);
_3 = copy ((*_1).1: u64);
_4 = copy ((*_1).2: [i8; 3]);
_0 = Foo { a: move _2, b: move _3, c: move _4 };
```
We can transform this to:
```
_0 = copy (*_1);
```
r? `@cjgillot`