Add support for clobber_abi to asm!
This PR adds the `clobber_abi` feature that was proposed in #81092.
Fixes#81092
cc `@rust-lang/wg-inline-asm`
r? `@nagisa`
Lint against named asm labels
This adds a deny-by-default lint to prevent the use of named labels in inline `asm!`. Without a solution to #81088 about whether the compiler should rewrite named labels or a special syntax for labels, a lint against them should prevent users from writing assembly that could break for internal compiler reasons, such as inlining or anything else that could change the number of actual inline assembly blocks emitted.
This does **not** resolve the issue with rewriting labels, that still needs a decision if the compiler should do any more work to try to make them work.
Try filtering out non-const impls when we expect const impls
**TL;DR**: Associated types on const impls are now bounded; we now disallow calling a const function with bounds when the specified type param only has a non-const impl.
r? `@oli-obk`
Name the captured upvars for closures/generators in debuginfo
Previously, debuggers print closures as something like
```
y::main::closure-0 (0x7fffffffdd34)
```
The pointer actually references to an upvar. It is not very obvious, especially for beginners.
It's because upvars don't have names before, as they are packed into a tuple. This PR names the upvars, so we can expect to see something like
```
y::main::closure-0 {_captured_ref__b: 0x[...]}
```
r? `@tmandry`
Discussed at https://github.com/rust-lang/rust/pull/84752#issuecomment-831639489 .
Associated functions that contain extern indicator or have `#[rustc_std_internal_symbol]` are reachable
Previously these fails to link with ``undefined reference to `foo'``:
<details>
<summary>Example 1</summary>
```rs
struct AssocFn;
impl AssocFn {
#[no_mangle]
fn foo() {}
}
fn main() {
extern "Rust" {
fn foo();
}
unsafe { foo() }
}
```
([Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=f1244afcdd26e2a28445f6e82ca46b50))
</details>
<details>
<summary>Example 2</summary>
```rs
#![crate_name = "lib"]
#![crate_type = "lib"]
struct AssocFn;
impl AssocFn {
#[no_mangle]
fn foo() {}
}
```
```rs
extern crate lib;
fn main() {
extern "Rust" {
fn foo();
}
unsafe { foo() }
}
```
</details>
But I believe they should link successfully, because this works:
<details>
```rs
#[no_mangle]
fn foo() {}
fn main() {
extern "Rust" {
fn foo();
}
unsafe { foo() }
}
```
([Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=789b3f283ee6126f53939429103ed98d))
</details>
This PR fixes the problem, by adding associated functions that have "custom linkage" to `reachable_set`, just like normal functions.
I haven't tested whether #76211 and [Miri](https://github.com/rust-lang/miri/issues/1837) are fixed by this PR yet, but I'm submitting this anyway since this fixes the examples above.
I added a `run-pass` test that combines my two examples above, but I'm not sure if that's the right way to test this. Maybe I should add / modify an existing codegen test (`src/test/codegen/export-no-mangle.rs`?) instead?
Revert "Rollup merge of #87779 - Aaron1011:stmt-ast-id, r=petrochenkov"
Fixes#87877
This change interacts badly with `noop_flat_map_stmt`,
which synthesizes multiple statements with the same `NodeId`.
I'm working on a better fix that will still allow us to
remove this special case. For now, let's revert the change
to fix the ICE.
This reverts commit a4262cc984, reversing
changes made to 8ee962f88e.
Avoid ICE caused by suggestion
When suggesting dereferencing something that can be iterable in a `for`
loop, erase lifetimes and use a fresh `ty::ParamEnv` to avoid 'region
constraints already solved' panic.
Fix#87657, fix#87709, fix#87651.
Fix closure migration suggestion when the body is a macro.
Fixes https://github.com/rust-lang/rust/issues/87955
Before:
```
warning: changes to closure capture in Rust 2021 will affect drop order
--> src/main.rs:5:13
|
5 | let _ = || panic!(a.0);
| ^^^^^^^^^^---^
| |
| in Rust 2018, closure captures all of `a`, but in Rust 2021, it only captures `a.0`
6 | }
| - in Rust 2018, `a` would be dropped here, but in Rust 2021, only `a.0` would be dropped here alongside the closure
|
help: add a dummy let to cause `a` to be fully captured
|
20~ ($msg:expr $(,)?) => ({ let _ = &a;
21+ $crate::rt::begin_panic($msg)
22~ }),
|
```
After:
```
warning: changes to closure capture in Rust 2021 will affect drop order
--> src/main.rs:5:13
|
5 | let _ = || panic!(a.0);
| ^^^^^^^^^^---^
| |
| in Rust 2018, closure captures all of `a`, but in Rust 2021, it only captures `a.0`
6 | }
| - in Rust 2018, `a` would be dropped here, but in Rust 2021, only `a.0` would be dropped here alongside the closure
|
help: add a dummy let to cause `a` to be fully captured
|
5 | let _ = || { let _ = &a; panic!(a.0) };
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
```
Implement `black_box` using intrinsic
Introduce `black_box` intrinsic, as suggested in https://github.com/rust-lang/rust/pull/87590#discussion_r680468700.
This is still codegenned as empty inline assembly for LLVM. For MIR interpretation and cranelift it's treated as identity.
cc `@Amanieu` as this is related to inline assembly
cc `@bjorn3` for rustc_codegen_cranelift changes
cc `@RalfJung` as this affects MIRI
r? `@nagisa` I suppose
When an incremental fingerprint mismatch occurs, we debug-print
our `DepNode` and query result. Unfortunately, the debug printing
process may cause us to run additional queries, which can result
in a re-entrant fingerprint mismatch error.
To avoid a double panic, this commit adds a thread-local variable
to detect re-entrant calls.
Silence non_fmt_panic from external macros.
This stops the non_fmt_panic lint from triggering if a macro from another crate is entirely responsible. In those cases there's nothing that the current crate can/should do.
See also https://github.com/rust-lang/rust/issues/87621#issuecomment-890311054
Improve formatting of closure capture migration suggestion for multi-line closures.
Fixes https://github.com/rust-lang/rust/issues/87952
Before:
```
help: add a dummy let to cause `a` to be fully captured
|
5 ~ let _ = || { let _ = &a;
6 + dbg!(a.0);
7 ~ };
|
```
After:
```
help: add a dummy let to cause `a` to be fully captured
|
5 ~ let _ = || {
6 + let _ = &a;
7 + dbg!(a.0);
8 ~ };
|
```
Add c_enum_min_bits target spec field, use for arm-none and thumb-none targets
Fixes https://github.com/rust-lang/rust/issues/87917
<s>Haven't tested this yet, still playing around.</s>
This seems to fix the issue.
Implement `black_box` using intrinsic
Introduce `black_box` intrinsic, as suggested in https://github.com/rust-lang/rust/pull/87590#discussion_r680468700.
This is still codegenned as empty inline assembly for LLVM. For MIR interpretation and cranelift it's treated as identity.
cc `@Amanieu` as this is related to inline assembly
cc `@bjorn3` for rustc_codegen_cranelift changes
cc `@RalfJung` as this affects MIRI
r? `@nagisa` I suppose
The new implementation allows some `memcpy`s to be optimized away,
so the uninit value in ui/sanitize/memory.rs is constructed directly
onto the return place. Therefore the sanitizer now says that the
value is allocated by `main` rather than `random`.
Fixes#87877
This change interacts badly with `noop_flat_map_stmt`,
which synthesizes multiple statements with the same `NodeId`.
I'm working on a better fix that will still allow us to
remove this special case. For now, let's revert the change
to fix the ICE.
This reverts commit a4262cc984, reversing
changes made to 8ee962f88e.
Link to edition guide instead of issues for 2021 lints.
This changes the 2021 lints to not link to github issues, but to the edition guide instead.
Fixes #86996
Use a more accurate span on assoc types WF checks
Before
```
error[E0275]: overflow evaluating the requirement `<FooStruct as Foo>::A == _`
--> $DIR/issue-21946.rs:8:5
|
LL | type A = <FooStruct as Foo>::A;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
after
```
error[E0275]: overflow evaluating the requirement `<FooStruct as Foo>::A == _`
--> $DIR/issue-21946.rs:8:14
|
LL | type A = <FooStruct as Foo>::A;
| ^^^^^^^^^^^^^^^^^^^^^
```
STD support for the ESP-IDF framework
Dear all,
This PR is implementing libStd support for the [ESP-IDF](https://github.com/espressif/esp-idf) newlib-based framework, which is the open source SDK provided by Espressif for their MCU family (esp32, esp32s2, esp32c3 and all other forthcoming ones).
Note that this PR has a [sibling PR](https://github.com/rust-lang/libc/pull/2310) against the libc crate, which implements proper declarations for all ESP-IDF APIs which are necessary for libStd support.
# Implementation approach
The ESP-IDF framework - despite being bare metal - offers a relatively complete POSIX API based on newlib. `pthread`, BSD sockets, file descriptors, and even a small file-system VFS layer. Perhaps the only significant exception is the lack of support for processes, which is to be expected of course on bare metal.
Therefore, the libStd support is implemented as a set of (hopefully small) changes to the `sys/unix` family of modules, in the form of conditional-compilation branches based either on `target_os = "espidf"` or in a couple of cases - based on `target_env = "newlib"` (the latter was already there actually and is not part of this patch).
The PR also contains two new targets:
- `riscv32imc-esp-espidf`
- `riscv32imac-esp-espidf`
... which are essentially copies of `riscv32imc-unknown-none-elf` and `riscv32imac-unknown-none-elf`, but enriched with proper `linker`, `linker_flavor`, `families`, `os`, `env` etc. specifications so that (a) the proper conditional compilation branches in libStd are selected when compiling with these targets and (b) the correct linker is used.
Since support for atomics is a precondition for libStd, the `riscv32imc-esp-espidf` target additionally is configured in such a way, so as to emit libcalls to the `__sync*` & `__atomic*` GCC functions, which are already implemented in the ESP-IDF framework. If this modification is not acceptable, we can also live with only the `riscv32imac-esp-espidf` target as well. While the RiscV chips of Espressif lack native atomics support, the relevant instructions are transparently emulated in the ESP-IDF framework using invalid instruction trap. This modification was implemented specifically with Rust support in mind.
# Target maintainers
In case this PR eventually gets merged, you can list myself as a Target Maintainer.
More importantly, Espressif (the chip vendor) is now actively involved and [embracing](https://github.com/espressif/rust-esp32-example/blob/main/docs/rust-on-xtensa.md) all [Rust-related efforts](https://github.com/esp-rs) which were originally a community effort. In light of that, I suppose `@MabezDev` - who initiated the Rust-on-Espressif efforts back in time and who now works for Espressif won't object to being listed as a maintainer as well.
**EDIT:** I was hinted (thanks, `@Urgau)` that answering the Tier 3 policy explicitly might be helpful. Answers below.
# Tier 3 Target Policy - answers
> A proposed target or target-specific patch that substantially changes code shared with other targets (not just target-specific code) must be reviewed and approved by the appropriate team for that shared code before acceptance.
Hopefully, the changes introduced by the ESP-IDF libStd support are rather on the small side. They are completely contained within the `sys/unix` set of modules (that is, aside from the obviously necessary one-liners in the `unwind` crate and in `build.rs`).
> 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.)
`@ivmarkov`
`@MabezDev`
> 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.
The two introduced targets follow as much as possible the naming conventions of the other targets. I.e. taking the bare-metal `riscv32imac_unknown_none_elf` as a base:
* The name of the new target was derived by replacing `none` with `espidf` to designate the `target_os`.
* `_elf` was removed, as the non-bare metal targets seem not to have it
* `-newlib` was deliberately NOT added at the end, as I believe the chance of having two simultaneously active separate targets for the ESP-IDF framework with different C libraries (say, newlib vs musl) is way too small
* Finally, we replaced the middle `unknown` with `esp` which is kind of the name of the whole chipset MCU family (and abbreviation from Espressif which is too long). It will stay `esp` for all RiscV32-based MCUs of the company, as they all use the riscv32imc instruction set. By necessity however (disambiguation), it will be `esp32` or `esp32s2` or `esp32s3` for the Xtensa-based MCUs as all of these have their own variation of the Xtensa architecture. (The Xtensa targets are not part of this PR, even though they would use 1:1 the same LibStd implementation provided here, as they depend on the upstreaming of the Xtensa architecture support in LLVM; this upstreaming this is currently in progress.)
There was also a preceding discussion on the topic [here](https://github.com/espressif/rust-esp32-example/issues/14).
> 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.
We are explicitly putting an `-espidf` suffix to designate that the target is *specifically* for Rust + ESP-IDF
> 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.
Agreed.
> The target must not introduce license incompatibilities.
To the best of our knowledge, it doesn't.
> Anything added to the Rust repository must be under the standard Rust license (MIT OR Apache-2.0).
MIT + 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.
Requirements are not changed for any other target.
> If the target supports building host tools (such as rustc or cargo), those host tools must not depend on proprietary (non-FOSS) libraries, other than ordinary runtime libraries supplied by the platform and commonly used by other binaries built for the target. 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.
The targets are for bare-metal environment which is not hosting build tools or a compiler.
> Targets should not require proprietary (non-FOSS) components to link a functional binary or library.
The linker used by the targets is the GCC linker from the GCC toolchain cross-compiled for riscv. GNU GPL.
> "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.
> 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.
Agreed.
> 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.
The targets implement libStd almost in its entirety, except for the missing support for process, as this is a bare metal platform. The process `sys\unix` module is currently stubbed to return "not implemented" errors.
> 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 tests (even if they do not pass), the documentation must explain how to run tests for the target, using emulation if possible or dedicated hardware if necessary.
Target does not (yet) support running tests. We would gladly provide all documentation how to build for the target (where?). It is currently hosted in this [README.md](https://github.com/ivmarkov/rust-esp32-std-hello) file, but will likely be moved to the [esp-rs](https://github.com/esp-rs) organization. Since the build for the target is driven by cargo and [all other tooling is downloaded automatically during the build](https://github.com/esp-rs/esp-idf-sys/blob/master/build.rs), there is no need for extensive documentation.
> 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.
Agreed.
> 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.
Agreed.
> 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.
To the best of our knowledge, we believe we are not breaking any other target (be it tier 1, 2 or 3).
> 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.
To the best of our knowledge, we have not introduced any unconditional use of a feature that affects any other target.
> If a tier 3 target stops meeting these requirements, or the target maintainers no longer have interest or time, or the target shows no signs of activity and has not built for some time, or removing the target would improve the quality of the Rust codebase, we may post a PR to remove it; any such PR will be CCed to the target maintainers (and potentially other people who have previously worked on the target), to check potential interest in improving the situation.
Agreed.
When suggesting dereferencing something that can be iterable in a `for`
loop, erase lifetimes and use a fresh `ty::ParamEnv` to avoid 'region
constraints already solved' panic.
Fix #87657.
Reduce verbosity of tracing output of RUSTC_LOG
The current output is really hard to read, I find, for things like trait selection. I nearly always end up removing these calls locally.
r? ```@oli-obk``` since you originally authored this
Plugin interface cleanup
The first commit performs two uncontroversial cleanups. The second commit removes `#[plugin_registrar]` and instead requires you to export a `__rustc_plugin_registrar` function, this will require a change to servo's script_plugins (cc `@jdm)`
* On suggestions that include deletions, use a diff inspired output format
* When suggesting addition, use `+` as underline
* Color highlight modified span
Various refactorings of the TAIT infrastructure
Before this PR we used to store the opaque type knowledge outside the `InferCtxt`, so it got recomputed on every opaque type instantiation.
I also removed a feature gate check that makes no sense in the planned lazy TAIT resolution scheme
Each commit passes all tests, so this PR is best reviewed commit by commit.
r? `@spastorino`
LLVM codegen: Don't emit zero-sized padding for fields
Currently padding is emitted before fields of a struct and at the end of the struct regardless of the ABI. Even if no padding is required zero-sized padding fields are emitted. This is not useful and - more importantly - it make it impossible to generate the exact vector types that LLVM expects for certain ARM SIMD intrinsics. This change should unblock the implementation of many ARM intrinsics using the `unadjusted` ABI, see https://github.com/rust-lang/stdarch/issues/1143#issuecomment-827404092.
This is a proof of concept only because the field lookup now takes O(number of fields) time compared to O(1) before since it recalculates the mapping at every lookup. I would like to find out how big the performance impact actually is before implementing caching or restricting this behavior to the `unadjusted` ABI.
cc `@SparrowLii` `@bjorn3`
([Discussion on internals](https://internals.rust-lang.org/t/feature-request-add-a-way-in-rustc-for-generating-struct-type-llvm-ir-without-paddings/15007))
typeck: don't suggest inaccessible fields in struct literals and suggest ignoring inaccessible fields in struct patterns
Fixes#87872.
This PR adjusts the missing field diagnostic logic in typeck so that when any of the missing fields in a struct literal or pattern is inaccessible then the error is less confusing, even if some of the missing fields are accessible.
See also #76524.
correctly handle enum variants in `opt_const_param_of`
Fixes#87542
`opt_const_param_of` was returning `None` for args on an enum variant `Enum::Variant::<10>` because we called `generics_of` on the enum variant which has no generics.
r? `@oli-obk`
* This commit adds the aarch64-unknown-uefi target and also adds it into
the supported targets list under the tier-3 target table.
* Uses the small code model by default
Signed-off-by: Andy-Python-Programmer <andypythonappdeveloper@gmail.com>
Fix feature gate checking of static-nobundle and native_link_modifiers
Feature native_link_modifiers_bundle don't need feature static-nobundle
to work.
Also check the feature gates when using native_link_modifiers from command line options. Current nighly compiler don't check those feature gate.
```
> touch lib.rs
> rustc +nightly lib.rs -L /usr/lib -l static:+bundle=dl --crate-type=rlib
> rustc +nightly lib.rs -L /usr/lib -l dylib:+as-needed=dl --crate-type=dylib -Ctarget-feature=-crt-static
> rustc +nightly lib.rs -L /usr/lib -l static:-bundle=dl --crate-type=rlib
error[E0658]: kind="static-nobundle" is unstable
|
= note: see issue #37403 <https://github.com/rust-lang/rust/issues/37403> for more information
= help: add `#![feature(static_nobundle)]` to the crate attributes to enable
error: aborting due to previous error
For more information about this error, try `rustc --explain E0658`.
```
First found this in https://github.com/rust-lang/rust/pull/85600#discussion_r676612655
Simplify typeck/primary_body_of, fix comment to match return signature
Hi, new contributor here! I'm carefully reading through the various modules just to learn. I noticed this function, `primary_body_of`, which has gone through a couple of refactors over time, adding new `Option`s to its returned tuple. Observations:
1. the `fn`'s documentation was not all up to date with the the current return signature.
2. `FnHeader` and `FnDecl` are always both `Some` or `None`. So I figured it might just return a reference to the full `hir::FnSig`, for simplicity and more precise typing. It's a pure refactor.
I'm learning better by working with code than just reading it, so here goes! If you want to avoid pure refactor PRs that don't really fix anything, I can revert the code change to only update the comment instead.
encode `generics_of` for fields and ty params
Fixes#87674Fixes#87603
ICE was caused by calling `generics_of` on a `DefId` without any `generics_of` results. This was happening when we call `generics_of` on parent `DefId`s of an unevaluated const when we evaluate it.
r? `@lcnr`
PassWrapper: handle move of OptimizationLevel class out of PassBuilder
This is the first build break of the LLVM 14 cycle, and was caused by
https://reviews.llvm.org/D107025. Mercifully an easy fix.
Move naked function ABI check to its own lint
This check was previously categorized under the lint named
`UNSUPPORTED_NAKED_FUNCTIONS`. That lint is future incompatible and will
be turned into an error in a future release. However, as defined in the
Constrained Naked Functions RFC, this check should only be a warning.
This is because it is possible for a naked function to be implemented in
such a way that it does not break even the undefined ABI. For example, a
`jmp` to a `const`.
Therefore, this patch defines a new lint named
`UNDEFINED_NAKED_FUNCTION_ABI` which contains just this single check.
Unlike `UNSUPPORTED_NAKED_FUNCTIONS`, `UNDEFINED_NAKED_FUNCTION_ABI`
will not be converted to an error in the future.
rust-lang/rfcs#2774rust-lang/rfcs#2972
Prepare call/invoke for opaque pointers
Rather than relying on `getPointerElementType()` from LLVM function
pointers, we now pass the function type explicitly when building `call`
or `invoke` instructions.
Hide allocator details from TryReserveError
I think there's [no need for TryReserveError to carry detailed information](https://github.com/rust-lang/rust/issues/48043#issuecomment-825139280), but I wouldn't want that issue to delay stabilization of the `try_reserve` feature.
So I'm proposing to stabilize `try_reserve` with a `TryReserveError` as an opaque structure, and if needed, expose error details later.
This PR moves the `enum` to an unstable inner `TryReserveErrorKind` that lives under a separate feature flag. `TryReserveErrorKind` could possibly be left as an implementation detail forever, and the `TryReserveError` get methods such as `allocation_size() -> Option<usize>` or `layout() -> Option<Layout>` instead, or the details could be dropped completely to make try-reserve errors just a unit struct, and thus smaller and cheaper.
Sync rustc_codegen_cranelift
05677b6bd6 removes two assertions that should have been removed in https://github.com/rust-lang/rust/pull/87515. They are no longer correct and trigger while compiling the sysroot.
r? `@ghost`
`@rustbot` label +A-codegen +A-cranelift +T-compiler
Remove special case for statement `NodeId` assignment
We now let `noop_flat_map_stmt` assign `NodeId`s (via `visit_id`),
just as we do for other AST nodes.
Add hint for unresolved associated trait items if the trait has a single item
This PR introduces a special-cased hint for unresolved trait items paths. It is shown if:
- the path was not resolved to any existing trait item
- and no existing trait item's name was reasonably close with regard to edit distance
- and the trait only has a single item in the corresponding namespace
I didn't know where I should put tests, therefore so far I just managed to bless two existing tests. I would be glad for hints where should tests for a hint like this be created, how should they be named (with reference to the original issue?) and what tests should I create (is it enough to test it just for types? or create separate tests also for functions and constants?).
It could also be turned into a machine applicable suggestion I suppose.
This is my first `rustc` PR, so please go easy on me :)
Fixes: https://github.com/rust-lang/rust/issues/87638
Fix overflow in rustc happening if the `err_count()` is reduced in a stage.
This can happen if stashed diagnostics are removed or replaced with fewer errors. The semantics stay the same if built without overflow checks. Fixes#84219.
Background: I came across this independently by running `RUSTFLAGS="-C overflow-checks=on" ./x.py test`. Fixing this will allow us to move on and find further overflow errors with testing or fuzzing.
This allows opaque type inference to check for defining uses without having to pass down that def id via function arguments to every method that could possibly cause an opaque type to be compared with a concrete type
Previously each opaque type instantiation would create new inference vars, even for the same opaque type/substs combination. Now there is a global map in InferCtxt that gets filled whenever we encounter an opaque type.
Rollup of 9 pull requests
Successful merges:
- #87561 (thread set_name haiku implementation.)
- #87715 (Add long error explanation for E0625)
- #87727 (explicit_generic_args_with_impl_trait: fix min expected number of generics)
- #87742 (Validate FFI-safety warnings on naked functions)
- #87756 (Add back -Zno-profiler-runtime)
- #87759 (Re-use std::sealed::Sealed in os/linux/process.)
- #87760 (Promote `aarch64-apple-ios-sim` to Tier 2)
- #87770 (permit drop impls with generic constants in where clauses)
- #87780 (alloc: Use intra doc links for the reserve function)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
permit drop impls with generic constants in where clauses
Fixes#79248
`==` is not sufficient to check for equality between unevaluated consts which causes the above issue because the const in `[(); N - 1]:` on the impl and the const in `[(); N - 1]:` on the struct def are not seen as equal. Any predicate that can contain an unevaluated const cant use `==` here as it will cause us to incorrectly emit an error.
I dont know much about chalk but it seems like we ought to be relating the `TypeWellFormedFromEnv` instead of `==` as it contains a `Ty` so I added that too...
r? ``````@lcnr``````
Add back -Zno-profiler-runtime
This was removed by #85284 in favor of `-Zprofiler-runtime=<name>`.However the suggested `-Zprofiler-runtime=None` doesn't work because`None` is treated as a crate name.
explicit_generic_args_with_impl_trait: fix min expected number of generics
Fixes#87718
The problem was that `synth_type_param_count` was already subtracted from `named_type_param_count`, so this ended up being subtracted again. This caused `expected_min` to overflow, and ultimately resulting in weird and wrong behaviour.
I've also added another test not present in the original issue but caused by the same bug.
The indexes into the VaListImpl struct used on aarch64 ABI (not macos/ios) are hard-coded which is brittle so we replace them with the usual lookup.
The varargs ffi is tested in ui/abi/variadic-ffi.rs on aarch64 Linux.
Rather than relying on `getPointerElementType()` from LLVM function
pointers, we now pass the function type explicitly when building `call`
or `invoke` instructions.
Disable unused variable lint for naked functions
In most calling conventions, accessing function parameters may require
stack access. However, naked functions have no assembly prelude to set
up stack access. This is why naked functions may only contain a single
`asm!()` block. All parameter access is done inside the `asm!()` block,
so we cannot validate the liveness of the input parameters. Therefore,
we should disable the lint for naked functions.
rust-lang/rfcs#2774rust-lang/rfcs#2972
`@joshtriplett` `@Amanieu` `@haraldh`
Allow more "unknown argument" strings from linker
Some toolchains emit slightly different errors, e.g.
ppc-vle-gcc: error: unrecognized option '-no-pie'
emit_aapcs_va_arg() emits hardcoded field indexes to access the
aarch64-specific `VaListImpl` struct. Due to the removed padding
those indexes have changed.
LLVM codegen: Don't emit zero-sized padding for whiles because that has no use and makes it impossible to generate the return types that LLVM expects for certain ARM SIMD intrinsics.
rustc: Fill out remaining parts of C-unwind ABI
This commit intends to fill out some of the remaining pieces of the
C-unwind ABI. This has a number of other changes with it though to move
this design space forward a bit. Notably contained within here is:
* On `panic=unwind`, the `extern "C"` ABI is now considered as "may
unwind". This fixes a longstanding soundness issue where if you
`panic!()` in an `extern "C"` function defined in Rust that's actually
UB because the LLVM representation for the function has the `nounwind`
attribute, but then you unwind.
* Whether or not a function unwinds now mainly considers the ABI of the
function instead of first checking the panic strategy. This fixes a
miscompile of `extern "C-unwind"` with `panic=abort` because that ABI
can still unwind.
* The aborting stub for non-unwinding ABIs with `panic=unwind` has been
reimplemented. Previously this was done as a small tweak during MIR
generation, but this has been moved to a separate and dedicated MIR
pass. This new pass will, for appropriate functions and function
calls, insert a `cleanup` landing pad for any function call that may
unwind within a function that is itself not allowed to unwind. Note
that this subtly changes some behavior from before where previously on
an unwind which was caught-to-abort it would run active destructors in
the function, and now it simply immediately aborts the process.
* The `#[unwind]` attribute has been removed and all users in tests and
such are now using `C-unwind` and `#![feature(c_unwind)]`.
I think this is largely the last piece of the RFC to implement.
Unfortunately I believe this is still not stabilizable as-is because
activating the feature gate changes the behavior of the existing `extern
"C"` ABI in a way that has no replacement. My thinking for how to enable
this is that we add support for the `C-unwind` ABI on stable Rust first,
and then after it hits stable we change the behavior of the `C` ABI.
That way anyone straddling stable/beta/nightly can switch to `C-unwind`
safely.
In most calling conventions, accessing function parameters may require
stack access. However, naked functions have no assembly prelude to set
up stack access. This is why naked functions may only contain a single
`asm!()` block. All parameter access is done inside the `asm!()` block,
so we cannot validate the liveness of the input parameters. Therefore,
we should disable the lint for naked functions.
rust-lang/rfcs#2774rust-lang/rfcs#2972
This check was previously categorized under the lint named
`UNSUPPORTED_NAKED_FUNCTIONS`. That lint is future incompatible and will
be turned into an error in a future release. However, as defined in the
Constrained Naked Functions RFC, this check should only be a warning.
This is because it is possible for a naked function to be implemented in
such a way that it does not break even the undefined ABI. For example, a
`jmp` to a `const`.
Therefore, this patch defines a new lint named
`UNDEFINED_NAKED_FUNCTION_ABI` which contains just this single check.
Unlike `UNSUPPORTED_NAKED_FUNCTIONS`, `UNDEFINED_NAKED_FUNCTION_ABI`
will not be converted to an error in the future.
rust-lang/rfcs#2774rust-lang/rfcs#2972
Remove unnecessary trailing whitespace from error messages
Some error messages currently contain unnecessary trailing whitespace. There are some legitimate reasons for having trailing whitespace in the output, such as for uniform indentation of possibly-empty input lines, but the whitespace I have addressed here occurs in a line used only for spacing, and I see no reason why that should have trailing whitespace (spacing lines inserted in other places also don't have trailing whitespace).
I have also removed a superfluous call to `buffer.putc()`, which has no effect because the same character is already placed there by `draw_col_separator()`.
Use `git diff --ignore-space-at-eol` to see my changes; otherwise the diff is quite large due to the whitespace removed from expected outputs in `src/test/ui/`.
This was removed by #85284 in favor of -Zprofiler-runtime=<name>.
However the suggested -Zprofiler-runtime=None doesn't work because
"None" is treated as a crate name.
Allow labeled loops as value expressions for `break`
Fixes#86948. This is currently allowed:
```rust
return 'label: loop { break 'label 42; };
break ('label: loop { break 'label 42; });
break 1 + 'label: loop { break 'label 42; };
break 'outer 'inner: loop { break 'inner 42; };
```
But not this:
```rust
break 'label: loop { break 'label 42; };
```
I have fixed this, so that the above now parses as an unlabeled break with a labeled loop as its value expression.
rustc: Replace `HirId`s with `LocalDefId`s in `AccessLevels` tables
and passes using those tables - primarily privacy checking, stability checking and dead code checking.
All these passes work with definitions rather than with arbitrary HIR nodes.
r? `@cjgillot`
cc `@lambinoo` (#87487)
Remove the aarch64 `crypto` target_feature
The subfeatures `aes` or `sha2` should be used instead.
This can't yet be done for ARM targets as some LLVM intrinsics still require `crypto`.
Also update the runtime feature detection tests in `library/std` to mirror the updates in `stdarch`. This also helps https://github.com/rust-lang/rust/issues/86941
r? ``@Amanieu``
Remove space after negative sign in Literal to_string
Negative proc macro literal tokens used to be printed with a space between the minus sign and the magnitude. That's because `impl ToString for Literal` used to convert the Literal into a TokenStream, which splits the minus sign into a separate Punct token.
```rust
Literal::isize_unsuffixed(-10).to_string() // "- 10"
```
This PR updates the ToString impl to directly use `rustc_ast::token::Lit`'s ToString, which matches the way Rust negative numbers are idiomatically written without a space.
```rust
Literal::isize_unsuffixed(-10).to_string() // "-10"
```
Places are usually shallow and quick to visit. By contrast, computing
`is_freeze` can be much costlier, involving inference and trait
solving. Making sure to call `is_freeze` only when necessary should be
beneficial for performance in most cases.
Remove invalid suggestion involving `Fn` trait bound
This pull request closes#85735. The actual issue is a duplicate of #21974, but #85735 contains a further problem, which is an invalid suggestion if `Fn`/`FnMut`/`FnOnce` trait bounds are involved: The suggestion code checks whether the trait bound ends with `>` to determine whether it has any generic arguments, but the `Fn*` traits have a special syntax for generic arguments that doesn't involve angle brackets. The example given in #85735:
```rust
trait Foo {}
impl<'a, 'b, T> Foo for T
where
T: FnMut(&'a ()),
T: FnMut(&'b ()), {
}
```
currently produces:
```
error[E0283]: type annotations needed
--> src/lib.rs:4:8
|
4 | T: FnMut(&'a ()),
| ^^^^^^^^^^^^^ cannot infer type for type parameter `T`
|
= note: cannot satisfy `T: FnMut<(&'a (),)>`
help: consider specifying the type arguments in the function call
|
4 | T: FnMut(&'a ())::<Self, Args>,
| ^^^^^^^^^^^^^^
error: aborting due to previous error
```
which is incorrect, because there is no function call, and applying the suggestion would lead to a parse error. With my changes, I get:
```
error[E0283]: type annotations needed
--> test.rs:4:8
|
4 | T: FnMut(&'a ()),
| ^^^^^^^^^^^^^ cannot infer type for type parameter `T`
|
::: [...]/library/core/src/ops/function.rs:147:1
|
147 | pub trait FnMut<Args>: FnOnce<Args> {
| ----------------------------------- required by this bound in `FnMut`
|
= note: cannot satisfy `T: FnMut<(&'a (),)>`
error: aborting due to previous error
```
i.e. I have added a check to prevent the invalid suggestion from being issued for `Fn*` bounds, while the underlying issue #21974 remains for now.