Rollup of 4 pull requests
Successful merges:
- #116675 ([ptr] Document maximum allocation size)
- #124997 (Fix ICE while casting a type with error)
- #125072 (Add test for dynamic dispatch + Pin::new soundness)
- #125090 (Migrate fuchsia docs from `pm` to `ffx`)
r? `@ghost`
`@rustbot` modify labels: rollup
Remove `NtIdent` and `NtLifetime`
This is one part of the bigger "remove `Nonterminal` and `TokenKind::Interpolated`" change drafted in #114647. More details in the individual commit messages.
r? `@petrochenkov`
Split out `ty::AliasTerm` from `ty::AliasTy`
Splitting out `AliasTerm` (for use in project and normalizes goals) and `AliasTy` (for use in `ty::Alias`)
r? lcnr
Rewrite 3 very similar `run-make` alloc tests to rmake
Part of #121876#121918 attempted to port these 3 tests 2 months ago. However, since then, the structure of `run-make-support` has changed a bit and new helper functions were added. Since there has been no activity on the PR, they are good low-hanging fruit to knock down, using the new functions of the current library.
There is also the removal of a useless import on a very similar test.
Unify `Rvalue::Aggregate` paths in cg_ssa
In #123840 and #123886 I added two different codepaths for `Rvalue::Aggregate` in `cg_ssa`.
This merges them into one, since raw pointers are also immediates that can be built from the immediates of their "fields".
This span records the declaration of the metavariable in the LHS of the macro.
It's used in a couple of error messages. Unfortunately, it gets in the way of
the long-term goal of removing `TokenKind::Interpolated`. So this commit
removes it, which degrades a couple of (obscure) error messages but makes
things simpler and enables the next commit.
Pretty-print let-else with added parenthesization when needed
Rustc used to produce invalid syntax for the following code, which is problematic because it means we cannot apply rustfmt to the output of `-Zunpretty=expanded`.
```rust
macro_rules! expr {
($e:expr) => { $e };
}
fn main() {
let _ = expr!(loop {}) else { return; };
}
```
```console
$ rustc repro.rs -Zunpretty=expanded | rustfmt
error: `loop...else` loops are not supported
--> <stdin>:9:29
|
9 | fn main() { let _ = loop {} else { return; }; }
| ---- ^^^^^^^^^^^^^^^^
| |
| `else` is attached to this loop
|
= note: consider moving this `else` clause to a separate `if` statement and use a `bool` variable to control if it should run
```
Unfortunately, we can't always offer a machine-applicable suggestion when there are subpatterns from macro expansion.
Co-Authored-By: Guillaume Boisseau <Nadrieril@users.noreply.github.com>
Fix some minor issues from the ui-test auto-porting
I'm not sure if these count as false positives, because well, starting a comment with `// incremental` was probably a valid compiletest directive.
But anyway, these tests directives became clearly goofy and now with the better syntax we can straighten things out.
r? jieyouxu
Migrate rustdoc scrape examples ordering
Part of https://github.com/rust-lang/rust/issues/121876.
This one adds a lot of utility methods/functions. To prevent having too much changes at once, I didn't make the existing rmake tests use these yet but I'll send a follow-up so they all use it.
r? `@jieyouxu`
Fix, document, and test parser and pretty-printer edge cases related to braced macro calls
_Review note: this is a deceptively small PR because it comes with 145 lines of docs and 196 lines of tests, and only 25 lines of compiler code changed. However, I recommend reviewing it 1 commit at a time because much of the effect of the code changes is non-local i.e. affecting code that is not visible in the final state of the PR. I have paid attention that reviewing the PR one commit at a time is as easy as I can make it. All of the code you need to know about is touched in those commits, even if some of those changes disappear by the end of the stack._
This is a follow-up to https://github.com/rust-lang/rust/pull/119105. One case that is not relevant to `-Zunpretty=expanded`, but which came up as I'm porting #119105 and #118726 into `syn`'s printer and `prettyplease`'s printer where it **is** relevant, and is also relevant to rustc's `stringify!`, is statement boundaries in the vicinity of braced macro calls.
Rustc's AST pretty-printer produces invalid syntax for statements that begin with a braced macro call:
```rust
macro_rules! stringify_item {
($i:item) => {
stringify!($i)
};
}
macro_rules! repro {
($e:expr) => {
stringify_item!(fn main() { $e + 1; })
};
}
fn main() {
println!("{}", repro!(m! {}));
}
```
**Before this PR:** output is not valid Rust syntax.
```console
fn main() { m! {} + 1; }
```
```console
error: leading `+` is not supported
--> <anon>:1:19
|
1 | fn main() { m! {} + 1; }
| ^ unexpected `+`
|
help: try removing the `+`
|
1 - fn main() { m! {} + 1; }
1 + fn main() { m! {} 1; }
|
```
**After this PR:** valid syntax.
```console
fn main() { (m! {}) + 1; }
```
The change to the test is a little goofy because the compiler was
guessing "correctly" before that `falsy! {}` is the condition as opposed
to the else body. But I believe this change is fundamentally correct.
Braced macro invocations in statement position are most often item-like
(`thread_local! {...}`) as opposed to parenthesized macro invocations
which are condition-like (`cfg!(...)`).
Always hide private fields in aliased type
This PR adds a new rustdoc pass that unconditionally always strips all private fields in aliased type, since showing them, even with `--document-private-items`, is confusing, unhelpful, and run backwards to the "Aliased type" feature, which is to show the type as it would be seen by the user.
r? ```@GuillaumeGomez```
Fixes#124938Fixes#123860
Clean up users of rust_dbg_call
`rust_dbg_call` is a C test helper that until this PR was declared in C with `void*` arguments and used in Rust _mostly_ with `libc::uintptr_t` arguments. Nearly every user just wants to pass integers around, so I've changed all users to `uint64_t` or `u64`.
The single test that actually used the pointer-ness of the argument is a test for ensuring that Rust can make extern calls outside of tasks. Rust hasn't had tasks for quite a few years now, so I'm deleting that test under the same logic as the test deleted in https://github.com/rust-lang/rust/pull/124073
Make sure we consume a generic arg when checking mistyped turbofish
When recovering un-turbofish-ed args in expr position (e.g. `let x = a<T, U>();` in `check_mistyped_turbofish_with_multiple_type_params`, we used `parse_seq_to_before_end` to parse the fake generic args; however, it used `parse_generic_arg` which *optionally* parses a generic arg. If it doesn't end up parsing an arg, it returns `Ok(None)` and consumes no tokens. If we don't find a delimiter after this (`,`), we try parsing *another* element. In this case, we just infinitely loop looking for a subsequent element.
We can fix this by making sure that we either parse a generic arg or error in `parse_seq_to_before_end`'s callback.
Fixes#124897
ignore generics args in attribute paths
Fixes#97006Fixes#123911Fixes#123912
This patch ensures that we no longer have to handle invalid generic arguments in attribute paths.
r? `@petrochenkov`
Avoid `alloca`s in codegen for simple `mir::Aggregate` statements
The core idea here is to remove the abstraction penalty of simple newtypes in codegen.
Even something simple like constructing a
```rust
#[repr(transparent)] struct Foo(u32);
```
forces an `alloca` to be generated in nightly right now.
Certainly LLVM can optimize that away, but it would be nice if it didn't have to.
Quick example:
```rust
#[repr(transparent)]
pub struct Transparent32(u32);
#[no_mangle]
pub fn make_transparent(x: u32) -> Transparent32 {
let a = Transparent32(x);
a
}
```
on nightly we produce <https://rust.godbolt.org/z/zcvoM79ae>
```llvm
define noundef i32 `@make_transparent(i32` noundef %x) unnamed_addr #0 {
%a = alloca i32, align 4
store i32 %x, ptr %a, align 4
%0 = load i32, ptr %a, align 4, !noundef !3
ret i32 %0
}
```
but after this PR we produce
```llvm
define noundef i32 `@make_transparent(i32` noundef %x) unnamed_addr #0 {
start:
ret i32 %x
}
```
(even before the optimizer runs).
Refactor float `Primitive`s to a separate `Float` type
Now there are 4 of them, it makes sense to refactor `F16`, `F32`, `F64` and `F128` out of `Primitive` and into a separate `Float` type (like integers already are). This allows patterns like `F16 | F32 | F64 | F128` to be simplified into `Float(_)`, and is consistent with `ty::FloatTy`.
As a side effect, this PR also makes the `Ty::primitive_size` method work with `f16` and `f128`.
Tracking issue: #116909
`@rustbot` label +F-f16_and_f128
Fix parse error message for meta items
Addresses https://github.com/rust-lang/rust/issues/122796#issuecomment-2010803906, cc [``@]Thomasdezeeuw.``
For attrs inside of a macro like `#[doc(alias = $ident)]` or `#[cfg(feature = $ident)]` where `$ident` is a macro metavariable of fragment kind `ident`, we used to say the following when expanded (with `$ident` ⟼ `ident`):
```
error: expected unsuffixed literal or identifier, found `ident`
--> weird.rs:6:19
|
6 | #[cfg(feature = $ident)]
| ^^^^^^
...
11 | m!(id);
| ------ in this macro invocation
|
= note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info)
```
This was incorrect and caused confusion, justifiably so (see #122796).
In this position, we only accept/expect *unsuffixed literals* which consist of numeric & string literals as well as the boolean literals / the keywords / the reserved identifiers `false` & `true` **but not** arbitrary identifiers.
Furthermore, we used to suggest garbage when encountering unexpected non-identifier tokens:
```
error: expected unsuffixed literal, found `-`
--> weird.rs:16:17
|
16 | #[cfg(feature = -1)]
| ^
|
help: surround the identifier with quotation marks to parse it as a string
|
16 | #[cfg(feature =" "-1)]
| + +
```
Now we no longer do.
Display walltime benchmarks with subnanosecond precision
With modern CPUs running at more than one cycle per nanosecond the current precision is insufficient to resolve differences worth several cycles per iteration.
Granted, walltime benchmarks often are noisy but occasionally, especially when no allocations are involved, the difference really is just a few cycles.
example results when benchmarking 1-4 serialized ADD instructions and an empty bench body
```
running 4 tests
test add ... bench: 0.24 ns/iter (+/- 0.00)
test add2 ... bench: 0.48 ns/iter (+/- 0.01)
test add3 ... bench: 0.72 ns/iter (+/- 0.01)
test add4 ... bench: 0.96 ns/iter (+/- 0.01)
test empty ... bench: 0.24 ns/iter (+/- 0.00)
```
Document tests in the `run-make` directory (A to C)
Part of the #121876 project.
This PR adds comments to some `run-make` tests which lack one, explaining _what_ is being tested. If possible, a link to the relevant PR or Issue responsible for the test is also provided.
This will help the porting efforts to `rmake.rs`, and will also allow maintainers to focus efforts on tests which are more pertinent to port. For example, [this test](https://github.com/rust-lang/rust/blob/master/tests/run-make/cat-and-grep-sanity-check/Makefile) will become useless after all tests containing `CGREP` are successfully ported.
In order to simplify review and at the suggestion of Kobzol on the rust-lang #gsoc Zulip, only the first 23 comments are part of this PR. If it is merged, future PRs will ensue commenting the rest of the tests.
Could be an UI test:
- `dep-info-doesnt-run-much`
Add `ErrorGuaranteed` to `Recovered::Yes` and use it more.
The starting point for this was identical comments on two different fields, in `ast::VariantData::Struct` and `hir::VariantData::Struct`:
```
// FIXME: investigate making this a `Option<ErrorGuaranteed>`
recovered: bool
```
I tried that, and then found that I needed to add an `ErrorGuaranteed` to `Recovered::Yes`. Then I ended up using `Recovered` instead of `Option<ErrorGuaranteed>` for these two places and elsewhere, which required moving `ErrorGuaranteed` from `rustc_parse` to `rustc_ast`.
This makes things more consistent, because `Recovered` is used in more places, and there are fewer uses of `bool` and
`Option<ErrorGuaranteed>`. And safer, because it's difficult/impossible to set `recovered` to `Recovered::Yes` without having emitted an error.
r? `@oli-obk`
Tidy check for test revisions that are mentioned but not declared
If a `[revision]` name appears in a test header directive or error annotation, but isn't declared in the `//@ revisions:` header, that is almost always a mistake.
In cases where a revision needs to be temporarily disabled, adding it to an `//@ unused-revision-names:` header will suppress these checks for that name.
Adding the wildcard name `*` to the unused list will suppress these checks for the entire file.
(None of the tests actually use `*`; it's just there because it was easy to add and could be handy as an escape hatch when dealing with other problems.)
---
Most of the existing problems discovered by this check were fairly straightforward to fix (or ignore); the trickiest cases are in `borrowck` tests.
The starting point for this was identical comments on two different
fields, in `ast::VariantData::Struct` and `hir::VariantData::Struct`:
```
// FIXME: investigate making this a `Option<ErrorGuaranteed>`
recovered: bool
```
I tried that, and then found that I needed to add an `ErrorGuaranteed`
to `Recovered::Yes`. Then I ended up using `Recovered` instead of
`Option<ErrorGuaranteed>` for these two places and elsewhere, which
required moving `ErrorGuaranteed` from `rustc_parse` to `rustc_ast`.
This makes things more consistent, because `Recovered` is used in more
places, and there are fewer uses of `bool` and
`Option<ErrorGuaranteed>`. And safer, because it's difficult/impossible
to set `recovered` to `Recovered::Yes` without having emitted an error.
Do not add leading asterisk in the `PartialEq`
I think we should address this issue, however I am not exactly sure, if this is the right way to do it. It is related to the #123056.
Imagine the simplified code:
```rust
trait MyTrait {}
impl PartialEq for dyn MyTrait {
fn eq(&self, _other: &Self) -> bool {
true
}
}
#[derive(PartialEq)]
enum Bar {
Foo(Box<dyn MyTrait>),
}
```
On the nightly compiler, the `derive` produces invalid code with the weird error message:
```
error[E0507]: cannot move out of `*__arg1_0` which is behind a shared reference
--> src/main.rs:11:9
|
9 | #[derive(PartialEq)]
| --------- in this derive macro expansion
10 | enum Things {
11 | Foo(Box<dyn MyTrait>),
| ^^^^^^^^^^^^^^^^ move occurs because `*__arg1_0` has type `Box<dyn MyTrait>`, which does not implement the `Copy` trait
|
= note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info)
```
It may be related to the perfect derive problem, although requiring the _type_ to be `Copy` seems unfortunate because it is not necessary. Besides, we are adding the extra dereference only for the diagnostics?
Handle field projections like slice indexing in invalid_reference_casting
r? `@Urgau`
I saw the implementation in https://github.com/rust-lang/rust/pull/124761, and I was wondering if we also need to handle field access. We do. Without this PR, we get this errant diagnostic:
```
error: casting references to a bigger memory layout than the backing allocation is undefined behavior, even if the reference is unused
--> /home/ben/rust/tests/ui/lint/reference_casting.rs:262:18
|
LL | let r = &mut v.0;
| --- backing allocation comes from here
LL | let ptr = r as *mut i32 as *mut Vec3<i32>;
| ------------------------------- casting happend here
LL | unsafe { *ptr = Vec3(0, 0, 0) }
| ^^^^^^^^^^^^^^^^^^^^
|
= note: casting from `i32` (4 bytes) to `Vec3<i32>` (12 bytes)
```
Fix more ICEs in `diagnostic::on_unimplemented`
There were 8 other calls to `expect_local` left in `on_unimplemented.rs` -- all of which (afaict) could be turned into ICEs.
I would really like to see validation of `on_unimplemented` separated from parsing, so we only emit errors here:
a60f077c38/compiler/rustc_hir_analysis/src/check/check.rs (L836-L839)
...And gracefully fail instead when emitting trait predicate failures, not *ever* even trying to emit an error or a lint. But that's left for a separate PR.
r? `@estebank`
Fix Error Messages for `break` Inside Coroutines
Fixes#124495
Previously, `break` inside `gen` blocks and functions
were incorrectly identified to be enclosed by a closure.
This PR fixes it by displaying an appropriate error message
for async blocks, async closures, async functions, gen blocks,
gen closures, gen functions, async gen blocks, async gen closures
and async gen functions.
Note: gen closure and async gen closure are not supported by the
compiler yet but I have added an error message here assuming that
they might be implemented in the future.
~~Also, fixes grammar in a few places by replacing
`inside of a $coroutine` with `inside a $coroutine`.~~