`ast::Item` has an `ident` field.
- It's always non-empty for these item kinds: `ExternCrate`, `Static`,
`Const`, `Fn`, `Mod`, `TyAlias`, `Enum`, `Struct`, `Union`,
`Trait`, `TraitAlias`, `MacroDef`, `Delegation`.
- It's always empty for these item kinds: `Use`, `ForeignMod`,
`GlobalAsm`, `Impl`, `MacCall`, `DelegationMac`.
There is a similar story for `AssocItemKind` and `ForeignItemKind`.
Some sites that handle items check for an empty ident, some don't. This
is a very C-like way of doing things, but this is Rust, we have sum
types, we can do this properly and never forget to check for the
exceptional case and never YOLO possibly empty identifiers (or possibly
dummy spans) around and hope that things will work out.
The commit is large but it's mostly obvious plumbing work. Some notable
things.
- `ast::Item` got 8 bytes bigger. This could be avoided by boxing the
fields within some of the `ast::ItemKind` variants (specifically:
`Struct`, `Union`, `Enum`). I might do that in a follow-up; this
commit is big enough already.
- For the visitors: `FnKind` no longer needs an `ident` field because
the `Fn` within how has one.
- In the parser, the `ItemInfo` typedef is no longer needed. It was used
in various places to return an `Ident` alongside an `ItemKind`, but
now the `Ident` (if present) is within the `ItemKind`.
- In a few places I renamed identifier variables called `name` (or
`foo_name`) as `ident` (or `foo_ident`), to better match the type, and
because `name` is normally used for `Symbol`s. It's confusing to see
something like `foo_name.name`.
`expand_test_case` looks for any item with a `#[test_case]` attribute
and adds a `test_path_symbol` attribute to it while also fiddling with
the item's ident's span.
This is pretty weird, because `#[test_case]` is only valid on
`fn`/`const`/`static` items, as far as I can tell. But you don't
currently get an error or warning if you use it on other kinds of items.
This commit changes things so that a `#[test_case]` item is modified
only if it is `fn`/`const`/`static`. This is relevant for moving idents
from `Item` to `ItemKind`, because some item kinds don't have an ident,
e.g. `impl` blocks.
The commit also does the following.
- Renames a local variable `test_id` as `test_ident`.
- Changes a `const` to `static` in
`tests/ui/custom_test_frameworks/full.rs` to give the `static` case
some test coverage.
- Adds a `struct` and `impl` to the same test to give some test coverage
to the non-affected item kinds. These have a `FIXME` comment
identifying the weirdness here. Hopefully this will be useful
breadcrumbs for somebody else in the future.
Rollup of 6 pull requests
Successful merges:
- #138176 (Prefer built-in sized impls (and only sized impls) for rigid types always)
- #138749 (Fix closure recovery for missing block when return type is specified)
- #138842 (Emit `unused_attributes` for `#[inline]` on exported functions)
- #139153 (Encode synthetic by-move coroutine body with a different `DefPathData`)
- #139157 (Remove mention of `exhaustive_patterns` from `never` docs)
- #139167 (Remove Amanieu from the libs review rotation)
r? `@ghost`
`@rustbot` modify labels: rollup
Encode synthetic by-move coroutine body with a different `DefPathData`
See the included test. In the first revision rpass1, we have an async closure `{closure#0}` which has a coroutine as a child `{closure#0}::{closure#0}`. We synthesize a by-move coroutine body, which is `{closure#0}::{closure#1}` which depends on the mir_built query, which depends on the typeck query.
In the second revision rpass2, we've replaced the coroutine-closure by a closure with two children closure. Notably, the def path of the second child closure is the same as the synthetic def id from the last revision: `{closure#0}::{closure#1}`. When type-checking this closure, we end up trying to compute its def_span, which tries to fetch it from the incremental cache; this will try to force the dependencies from the last run, which ends up forcing the mir_built query, which ends up forcing the typeck query, which ends up with a query cycle.
The problem here is that we really should never have used the same `DefPathData` for the synthetic by-move coroutine body, since it's not a closure. Changing the `DefPathData` will mean that we can see that the def ids are distinct, which means we won't try to look up the closure's def span from the incremental cache, which will properly skip replaying the node's dependencies and avoid a query cycle.
Fixes#139142
Emit `unused_attributes` for `#[inline]` on exported functions
I saw someone post a code sample that contained these two attributes, which immediately made me suspicious.
My suspicions were confirmed when I did a small test and checked the compiler source code to confirm that in these cases, `#[inline]` is indeed ignored (because you can't exactly `LocalCopy`an unmangled symbol since that would lead to duplicate symbols, and doing a mix of an unmangled `GloballyShared` and mangled `LocalCopy` instantiation is too complicated for our current instatiation mode logic, which I don't want to change right now).
So instead, emit the usual unused attribute lint with a message saying that the attribute is ignored in this position.
I think this is not 100% true, since I expect LLVM `inlinehint` to still be applied to such a function, but that's not why people use this attribute, they use it for the `LocalCopy` instantiation mode, where it doesn't work.
r? saethlin as the instantiation guy
Procedurally, I think this should be fine to merge without any lang involvement, as this only does a very minor extension to an existing lint.
Fix closure recovery for missing block when return type is specified
Firstly, fix the `is_array_like_block` condition to make sure we're actually recovering a mistyped *block* rather than some other delimited expression. This fixes#138748.
Secondly, split out the recovery of missing braces on a closure body into a separate recovery. Right now, the suggestion `"you might have meant to write this as part of a block"` originates from `suggest_fixes_misparsed_for_loop_head`, which feels kinda brittle and coincidental since AFAICT that recovery wasn't ever really intended to fix this.
We also can make this `MachineApplicable` in this case.
Fixes#138748
r? `@fmease` or reassign if you're busy/don't wanna review this
Prefer built-in sized impls (and only sized impls) for rigid types always
This PR changes the confirmation of `Sized` obligations to unconditionally prefer the built-in impl, even if it has nested obligations. This also changes all other built-in impls (namely, `Copy`/`Clone`/`DiscriminantKind`/`Pointee`) to *not* prefer built-in impls over param-env impls. This aligns the old solver with the behavior of the new solver.
---
In the old solver, we register many builtin candidates with the `BuiltinCandidate { has_nested: bool }` candidate kind. The precedence this candidate takes over other candidates is based on the `has_nested` field. We only prefer builtin impls over param-env candidates if `has_nested` is `false`
2b4694a698/compiler/rustc_trait_selection/src/traits/select/mod.rs (L1804-L1866)
Preferring param-env candidates when the builtin candidate has nested obligations *still* ends up leading to detrimental inference guidance, like:
```rust
fn hello<T>() where (T,): Sized {
let x: (_,) = Default::default();
// ^^ The `Sized` obligation on the variable infers `_ = T`.
let x: (i32,) = x;
// We error here, both a type mismatch and also b/c `T: Default` doesn't hold.
}
```
Therefore this PR adjusts the candidate precedence of `Sized` obligations by making them a distinct candidate kind and unconditionally preferring them over all other candidate kinds.
Special-casing `Sized` this way is necessary as there are a lot of traits with a `Sized` super-trait bound, so a `&'a str: From<T>` where-bound results in an elaborated `&'a str: Sized` bound. People tend to not add explicit where-clauses which overlap with builtin impls, so this tends to not be an issue for other traits.
We don't know of any tests/crates which need preference for other builtin traits. As this causes builtin impls to diverge from user-written impls we would like to minimize the affected traits. Otherwise e.g. moving impls for tuples to std by using variadic generics would be a breaking change. For other builtin impls it's also easier for the preference of builtin impls over where-bounds to result in issues.
---
There are two ways preferring builtin impls over where-bounds can be incorrect and undesirable:
- applying the builtin impl results in undesirable region constraints. E.g. if only `MyType<'static>` implements `Copy` then a goal like `(MyType<'a>,): Copy` would require `'a == 'static` so we must not prefer it over a `(MyType<'a>,): Copy` where-bound
- this is mostly not an issue for `Sized` as all `Sized` impls are builtin and don't add any region constraints not already required for the type to be well-formed
- however, even with `Sized` this is still an issue if a nested goal also gets proven via a where-bound: [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=30377da5b8a88f654884ab4ebc72f52b)
- if the builtin impl has associated types, we should not prefer it over where-bounds when normalizing that associated type. This can result in normalization adding more region constraints than just proving trait bounds. https://github.com/rust-lang/rust/issues/133044
- not an issue for `Sized` as it doesn't have associated types.
r? lcnr
Revert "Rollup merge of #136127 - WaffleLapkin:dyn_ptr_unwrap_cast, r=compiler-errors"
...not permanently tho. Just until we can land something like #138542, which will fix the underlying perf issues (https://github.com/rust-lang/rust/pull/136127#issuecomment-2743891744). I just don't want this to land on beta and have people rely on this behavior if it'll need some reworking for it to be implemented performantly.
r? `@WaffleLapkin` or reassign -- sorry for reverting ur pr! i'm working on getting it re-landed soon :>
hygiene: Rewrite `apply_mark_internal` to be more understandable
The previous implementation allocated new `SyntaxContext`s in the inverted order, and it was generally very hard to understand why its result matches what the `opaque` and `opaque_and_semitransparent` field docs promise.
```rust
/// This context, but with all transparent and semi-transparent expansions filtered away.
opaque: SyntaxContext,
/// This context, but with all transparent expansions filtered away.
opaque_and_semitransparent: SyntaxContext,
```
It also couldn't be easily reused for the case where the context id is pre-reserved like in #129827.
The new implementation tries to follow the docs in a more straightforward way.
I did the transformation in small steps, so it indeed matches the old implementation, not just the docs.
So I suggest reading only the new version.
Improve hir_pretty for struct expressions.
While working on https://github.com/rust-lang/rust/pull/139131 I noticed the hir pretty printer outputs an empty line between each field, and is also missing a space before the `{` and the `}`:
```rust
let a =
StructWithSomeFields{
field_1: 1,
field_2: 2,
field_3: 3,
field_4: 4,
field_5: 5,
field_6: 6,};
let a = StructWithSomeFields{ field_1: 1, field_2: 2, ..a};
```
This changes it to:
```rust
let a =
StructWithSomeFields {
field_1: 1,
field_2: 2,
field_3: 3,
field_4: 4,
field_5: 5,
field_6: 6 };
let a = StructWithSomeFields { field_1: 1, field_2: 2, ..a };
```
Remove attribute `#[rustc_error]`
It was an ancient way to write `check-pass` tests, but now it's no longer necessary (except for the `delayed_bug_from_inside_query` flavor, which is retained).
Simplify expansion for format_args!().
Instead of calling `Placeholder::new()`, we can just use a struct expression directly.
Before:
```rust
Placeholder::new(…, …, …, …)
```
After:
```rust
Placeholder {
position: …,
flags: …,
width: …,
precision: …,
}
```
(I originally avoided the struct expression, because `Placeholder` had a lot of fields. But now that https://github.com/rust-lang/rust/pull/136974 is merged, it only has four fields left.)
This will make the `fmt` argument to `fmt::Arguments::new_v1_formatted()` a candidate for const promotion, which is important if we ever hope to tackle https://github.com/rust-lang/rust/issues/92698 (It doesn't change anything yet though, because the `args` argument to `fmt::Arguments::new_v1_formatted()` is not const-promotable.)
Subtree sync for rustc_codegen_cranelift
The main highlights this time are a Cranelift update, support for `#[target_feature]` for inline asm on arm64 and some vendor intrinsic fixes for arm64.
[AIX] Ignore linting on repr(C) structs with repr(packed) or repr(align(n))
This PR updates the lint added in 9b40bd7 to ignore repr(C) structs that also have repr(packed) or repr(align(n)).
As these representations can be modifiers on repr(C), it is assumed that users that add these should know what they are doing, and thus the the lint should not warn on the respective structs. For example, for the time being, using repr(packed) and manually padding a repr(C) struct can be done to correctly align struct members on AIX.
Instead of calling new(), we can just use a struct expression directly.
Before:
Placeholder::new(…, …, …, …)
After:
Placeholder {
position: …,
flags: …,
width: …,
precision: …,
}
Set `target_vendor = "openwrt"` on `mips64-openwrt-linux-musl`
OpenWRT is a Linux distribution for embedded network devices. The target name contains `openwrt`, so we should set `cfg(target_vendor = "openwrt")`.
This is similar to what other Linux distributions do (the only one in-tree is `x86_64-unikraft-linux-musl`, but that sets `target_vendor = "unikraft"`).
Motivation: To make correctly [parsing target names](https://github.com/rust-lang/cc-rs/pull/1413) simpler.
Fixes https://github.com/rust-lang/rust/issues/131165.
CC target maintainer `@Itus-Shield`
Fix `uclibc` LLVM target triples
`uclibc` is not an environment understood by LLVM, it is only a concept in Clang that can be selected with `-muclibc` (it affects which dynamic linker is passed to the static linker's `-dynamic-linker` flag).
In fact, using `uclibcgnueabi`/`uclibc` is actively harmful, as it prevents LLVM from seeing that the target is gnu-like; we should use `gnueabi`/`gnu` directly instead.
Motivation: To make it easier to verify that [`cc-rs`' conversion from `rustc` to Clang/LLVM triples](https://github.com/rust-lang/cc-rs/issues/1431) is correct.
**There are no target maintainers for these targets.** So I'll CC ``@lancethepants`` and ``@skrap`` who maintain the related `armv7-unknown-linux-uclibceabi` and `armv7-unknown-linux-uclibceabihf` (both of which already pass `-gnu` instead of `-uclibc`) in case they have any insights.
r? jieyouxu
Remove `terminating_scopes` hash set.
Instead of inserting and checking ids in a hashset, we can just pass a boolean as argument.
For example:
```diff
- visitor.terminating_scopes.insert(arm.hir_id.local_id);
- visitor.enter_node_scope_with_dtor(arm.hir_id.local_id);
+ visitor.enter_node_scope_with_dtor(arm.hir_id.local_id, true);
```
Do not treat lifetimes from parent items as influencing child items
```rust
struct A;
impl Bar<'static> for A {
const STATIC: &str = "";
// ^ no future incompat warning
}
```
has no future incompat warning, because there is no ambiguity. But
```rust
struct C;
impl Bar<'_> for C {
// ^^ this lifeimte
const STATIC: &'static str = {
struct B;
impl Bar<'static> for B {
const STATIC: &str = "";
// causes ^ to emit a future incompat warning
}
""
};
}
```
had one before this PR, because the impl for `B` (which is just a copy of `A`) thought it was influenced by a lifetime on the impl for `C`.
I double checked all other `lifetime_ribs` iterations and all of them do check for `Item` boundaries. This feels very fragile tho, and ~~I think we should do not even be able to see ribs from parent items, but that's a different refactoring that I'd rather not do at the same time as a bugfix~~. EDIT: ah nevermind, this is needed for improving diagnostics like "use of undeclared lifetime" being "can't use generic parameters from outer item" instead.
r? `@compiler-errors`