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.
Trait upcasting coercion (part2)
This is the second part of trait upcasting coercion implementation.
Currently this is blocked on #86264 .
The third part might be implemented using unsafety checking
r? `@bjorn3`
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.
Rollup of 8 pull requests
Successful merges:
- #87645 (Properly find owner of closure in THIR unsafeck)
- #87646 (Fix a parser ICE on invalid `fn` body)
- #87652 (Validate that naked functions are never inlined)
- #87685 (Write docs for SyncOnceCell From and Default impl)
- #87693 (Add `aarch64-apple-ios-sim` as a possible target to the manifest)
- #87708 (Add convenience method for handling ipv4-mapped addresses by canonicalizing them)
- #87711 (Correct typo)
- #87716 (Allow generic SIMD array element type)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Fix a parser ICE on invalid `fn` body
Fixes#87635
A better fix would add a check for `fn` body on `expected_one_of_not_found` but I haven't come up with a graceful way. Any idea?
r? ```@oli-obk``` ```@estebank```
Properly find owner of closure in THIR unsafeck
Previously, when encountering a closure in a constant, the THIR unsafeck gets invoked on the owner of the constant instead of the constant itself, producing cycles.
Supersedes #87492. ```@FabianWolff``` thanks for your work on that PR, I copied your test file and added you as a co-author.
Fixes#87414.
r? ```@oli-obk```
Support negative numbers in Literal::from_str
proc_macro::Literal has allowed negative numbers in a single literal token ever since Rust 1.29, using https://doc.rust-lang.org/stable/proc_macro/struct.Literal.html#method.isize_unsuffixed and similar constructors.
```rust
let lit = proc_macro::Literal::isize_unsuffixed(-10);
```
However, the suite of constructors on Literal is not sufficient for all use cases, for example arbitrary precision floats, or custom suffixes in FFI macros.
```rust
let lit = proc_macro::Literal::f64_unsuffixed(0.101001000100001000001000000100000001); // :(
let lit = proc_macro::Literal::i???_suffixed(10ulong); // :(
```
For those, macros construct the literal using from_str instead, which preserves arbitrary precision, custom suffixes, base, and digit grouping.
```rust
let lit = "0.101001000100001000001000000100000001".parse::<Literal>().unwrap();
let lit = "10ulong".parse::<Literal>().unwrap();
let lit = "0b1000_0100_0010_0001".parse::<Literal>().unwrap();
```
However, until this PR it was not possible to construct a literal token that is **both** negative **and** preserving of arbitrary precision etc.
This PR fixes `Literal::from_str` to recognize negative integer and float literals.
Implement a `explicit_generic_args_with_impl_trait` feature gate
Implements #83701
When this gate is enabled, explicit generic arguments can be specified even if `impl Trait` is used in argument position. Generic arguments can only be specified for explicit generic parameters but not for the synthetic type parameters from `impl Trait`
So code like this will be accepted:
```rust
#![feature(explicit_generic_args_with_impl_trait)]
fn foo<T: ?Sized>(_f: impl AsRef<T>) {}
fn main() {
foo::<str>("".to_string());
}
```
CTFE: throw unsupported error when partially overwriting a pointer
Currently, during CTFE, when a write to memory would overwrite parts of a pointer, we make the remaining parts of that pointer "uninitialized". This is probably not what users expect, so if this ever happens they will be quite confused about why some of the data just vanishes for seemingly no good reason.
So I propose we change this to abort CTFE when that happens, to at last avoid silently doing the wrong thing.
Cc https://github.com/rust-lang/rust/issues/87184
Our CTFE test suite still seems to pass. However, we should probably crater this, and I want to do some tests with Miri as well.
After this commit, `unsafe async fn ...` now suggests the `async unsafe` fix
instead of misunderstanding the issue.
This is not perfect for repeated keywords (`const async const`) and for
keywords that are misplaced after `extern "some abi"` because of the way
`check_fn_font_matter` works, but changing it breaks so many tests and
diagnostics it has been judged too high a cost for this PR.
rfc3052 followup: Remove authors field from Cargo manifests
Since RFC 3052 soft deprecated the authors field, hiding it from
crates.io, docs.rs, and making Cargo not add it by default, and it is
not generally up to date/useful information for contributors, we may as well
remove it from crates in this repo.
When this gate is enabled, explicit generic arguments can be specified even
if `impl Trait` is used in argument position. Generic arguments can only be
specified for explicit generic parameters but not for the synthetic type
parameters from `impl Trait`
Bump bootstrap compiler to 1.55
Changing the cfgs for stdarch is missing, but my understanding is that we don't need to do it as part of this PR?
r? `@Mark-Simulacrum`
Bail on any found recursion when expanding opaque types
Fixes#87450. More of a bandaid because it does not fix the exponential complexity of the type folding used for opaque type expansion.
Suggest `br` if the unknown string prefix `rb` is found
Currently, for the following code:
```rust
fn main() {
rb"abc";
}
```
we issue the following suggestion:
```
help: consider inserting whitespace here
|
2 | rb "abc";
| --
```
With my changes (only in edition 2021, where unknown prefixes became an error), I get:
```
help: use `br` for a raw byte string
|
2 | br"abc";
| ^^
```
Add a hint that the expressions produce a value
Fixes#85913
The second commit is semi-_unrelated_ but it allows us to run the related tests just on `src/test/ui/lint`.
Trait upcasting coercion (part1)
This revives the first part of earlier PR #60900 .
It's not very clear to me which parts of that pr was design decisions, so i decide to cut it into pieces and land them incrementally. This allows more eyes on the details.
This is the first part, it adds feature gates, adds feature gates tests, and implemented the unsize conversion part.
(I hope i have dealt with the `ExistentialTraitRef` values correctly...)
The next part will be implementing the pointer casting.
Rollup of 9 pull requests
Successful merges:
- #86072 (Cross compiling rustc_llvm on Darwin requires zlib.)
- #87385 (Make `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` warn by default)
- #87547 (Add missing examples for NonNull)
- #87557 (Fix issue with autofix for ambiguous associated function from Rust 2021 prelude when struct is generic)
- #87559 (Tweak borrowing suggestion in `for` loop)
- #87596 (Add warning when whitespace is not skipped after an escaped newline)
- #87606 (Add some TAIT-related regression tests)
- #87609 (Add docs about performance and `Iterator::map` to `[T; N]::map`)
- #87616 (Fix missing word in rustdoc book)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Add warning when whitespace is not skipped after an escaped newline
Fixes issue #87318, also simplifies issue #87319.
* Add support to the lexer to emit warnings as well as errors.
* Emit a warning when a string literal contains an escaped newline, but when (some of) the whitespace on the next line is not skipped due to it being non-ASCII.