Compare commits

...

1684 Commits
beta ... main

Author SHA1 Message Date
bors
4933094f25 Auto merge of #155851 - jhpratt:rollup-Jst4hhC, r=jhpratt
Some checks failed
Post merge analysis / analysis (push) Has been cancelled
GHCR image mirroring / DockerHub mirror (push) Has been cancelled
Bump dependencies in Cargo.lock / skip if S-waiting-on-bors (push) Has been cancelled
Bump dependencies in Cargo.lock / update dependencies (push) Has been cancelled
Bump dependencies in Cargo.lock / amend PR (push) Has been cancelled
Rollup of 12 pull requests

Successful merges:

 - rust-lang/rust#149624 (Fix requires_lto targets needing lto set in cargo)
 - rust-lang/rust#155317 (`std::io::Take`: Clarify & optimize `BorrowedBuf::set_init` usage.)
 - rust-lang/rust#155579 (Make Rcs and Arcs use pointer comparison for unsized types)
 - rust-lang/rust#155588 (Implement more traits for FRTs)
 - rust-lang/rust#155708 (Fix heap overflow in slice::join caused by misbehaving Borrow)
 - rust-lang/rust#155778 (Avoid Vec allocation in TyCtxt::mk_place_elem)
 - rust-lang/rust#151014 (std: sys: process: uefi: Add program searching)
 - rust-lang/rust#155682 (Add boxing suggestions for `impl Trait` return type mismatches)
 - rust-lang/rust#155770 (Avoid misleading closure return type note)
 - rust-lang/rust#155818 (Convert attribute `FinalizeFn` to fn pointer)
 - rust-lang/rust#155829 (rustc_attr_parsing: use a `try {}` in `or_malformed`)
 - rust-lang/rust#155835 (couple of `crate_name` cleanups)
2026-04-27 02:32:52 +00:00
Jacob Pratt
bd2d1a8443 Rollup merge of #155835 - jyn514:jyn/verify-ich-diagnostics, r=wesleywiser
couple of `crate_name` cleanups

Split out from https://github.com/rust-lang/rust/pull/153924; these changes should be uncontroversial.
2026-04-26 21:56:46 -04:00
Jacob Pratt
c0e4189058 Rollup merge of #155829 - scrabsha:push-kwlqypwmnpul, r=mejrs
rustc_attr_parsing: use a `try {}` in `or_malformed`
2026-04-26 21:56:45 -04:00
Jacob Pratt
3502ed31ec Rollup merge of #155818 - JonathanBrouwer:finalize-fn-ptr, r=mejrs
Convert attribute `FinalizeFn` to fn pointer
2026-04-26 21:56:44 -04:00
Jacob Pratt
78569d8d6a Rollup merge of #155770 - chenyukang:yukang-fix-155670-closure-return-note, r=wesleywiser
Avoid misleading closure return type note

Fixes rust-lang/rust#155670
2026-04-26 21:56:44 -04:00
Jacob Pratt
9562f3da2d Rollup merge of #155682 - Unique-Usman:ua/box-impl, r=mejrs
Add boxing suggestions for `impl Trait` return type mismatches

A sort of a follow up pr to this -> https://github.com/rust-lang/rust/pull/155546
2026-04-26 21:56:43 -04:00
Jacob Pratt
e3a6fa5082 Rollup merge of #151014 - Ayush1325:uefi-cmd-path, r=jhpratt,nicholasbishop
std: sys: process: uefi: Add program searching

- Follow UEFI Shell search flow to search for programs while launching.
- Tested using OVMF on QEMU.

@rustbot label +O-UEFI
2026-04-26 21:56:42 -04:00
Jacob Pratt
c20a92efd9 Rollup merge of #155778 - kevinheavey:perf-mk-place-elem-avoid-vec-alloc, r=cjgillot,JohnTitor
Avoid Vec allocation in TyCtxt::mk_place_elem

`mk_place_elem` appends a single `PlaceElem` to an existing (interned) projection. The current implementation copies the projection into a fresh `Vec`, pushes the new element, and re-interns the slice, which allocates on every call.

Feed the elements through `mk_place_elems_from_iter` so that `CollectAndApply`'s hand-unrolled stack fast path (up to 9 elements, in `rustc_type_ir::interner`) kicks in for the common case of short projections and the `Vec` allocation is skipped entirely. The behavior is identical for longer projections (the fast path falls back to a `Vec` internally).
2026-04-26 21:56:42 -04:00
Jacob Pratt
f4043f8c09 Rollup merge of #155708 - Manishearth:borrow-fix, r=Mark-Simulacrum
Fix heap overflow in slice::join caused by misbehaving Borrow

This code allocates a buffer using lengths calculated by calling `.borrow()` on some slices, and then copies them over after again calling `.borrow()`. There is no safety-reliable guarantee that these will return the same slices.

While this code calls `.borrow()` three times, only one of them is problematic: the others already use checked indexing.

I made the test a normal library test, but let me know if it should go elsewhere.

Bug discovered by Rust Foundation Security using AI. I'm just helping with the patch as a member of wg-security-response. We do not believe this bug needs embargo, it is a soundness fix for hard-to-trigger unsoundness.
2026-04-26 21:56:41 -04:00
Jacob Pratt
7695b849d4 Rollup merge of #155588 - BennoLossin:frt-traits, r=Mark-Simulacrum
Implement more traits for FRTs

From https://github.com/rust-lang/rust/pull/154927#discussion_r3068460955.

FRTs now implement the following traits: `Sized + Freeze + RefUnwindSafe + Send + Sync + Unpin + UnsafeUnpin + UnwindSafe + Copy + Debug + Default + Eq + Hash + Ord`.

Let me know if there is any trait missing.

I also removed the explicit  `Send` and `Sync` impls, since commit cb37ee2c87 ("make field representing types invariant over the base type") made the auto-trait impl work even if `T: !Send` or `T: !Sync`. Very happy to see unsafe impls get dropped :)

Note that I used the reflection feature (cc @oli-obk) to print the actual field names in the debug implementation. I think this is a cool way to use it, but if it isn't ready for that, I'm happy to change it to the alternative implementation I gave in the note comment (it's essentially Mark's suggestion but printing `T`'s name instead of `Self`'s).

Since this is a library change, I'll give this to Mark; feel free to also take a look/leave comments, Oli :)

r? @Mark-Simulacrum
2026-04-26 21:56:41 -04:00
Jacob Pratt
72cd5fba78 Rollup merge of #155579 - Gaming32:fix-154998, r=Mark-Simulacrum
Make Rcs and Arcs use pointer comparison for unsized types

`Rc` and `Arc`s have an `Eq` implementation that first attempt to compare the pointers as an optimization. This, however, was not extended to DSTs, which is what this PR fixes.

Fixes rust-lang/rust#154998.
2026-04-26 21:56:40 -04:00
Jacob Pratt
12a843a020 Rollup merge of #155317 - briansmith:b/take-opt, r=Mark-Simulacrum
`std::io::Take`: Clarify & optimize `BorrowedBuf::set_init` usage.

Don't initialize `buf` if it was already initialized. Clarify safety comments.

Move the `buf.advance()` call to make the initialization more like
calling `buf.ensure_init()`, then clarify how the code here is an
optimized variant of `ensure_init`.
2026-04-26 21:56:39 -04:00
Jacob Pratt
f8e3af446e Rollup merge of #149624 - Flakebi:fix-lto, r=bjorn3
Fix requires_lto targets needing lto set in cargo

Targets that set `requires_lto = true` were not actually using lto when compiling with cargo by default. They needed an extra `lto = true` in `Cargo.toml` to work.

Fix this by letting lto take precedence over the `embed_bitcode` flag when lto is required by a target.

If both these flags would be supplied by the user, an error is generated. However, this did not happen when lto was requested by the target instead of the user.

Fixes rust-lang/rust#148514
Tracking issue: rust-lang/rust#135024
2026-04-26 21:56:39 -04:00
Manish Goregaokar
da545d0856 Fix heap overflow in slice::join caused by misbehaving Borrow
* Fix heap overflow in slice join via inconsistent Borrow
* Update library/alloc/src/str.rs

Co-authored-by: Mark Rousskov <mark.simulacrum@gmail.com>
2026-04-26 23:20:32 +00:00
bors
ca9a134e09 Auto merge of #155837 - JonathanBrouwer:rollup-aPhy30j, r=JonathanBrouwer
Rollup of 15 pull requests

Successful merges:

 - rust-lang/rust#152995 (ACP Implementation of PermissionsExt for Windows )
 - rust-lang/rust#153457 (prevent deref coercions in `pin!`)
 - rust-lang/rust#155250 (Windows: Cache the pipe filesystem handle)
 - rust-lang/rust#155574 (Move `std::io::RawOsError` to `core::io`)
 - rust-lang/rust#155757 (macro_metavar_expr_concat: explain why idents are invalid)
 - rust-lang/rust#155823 (miri subtree update)
 - rust-lang/rust#155693 (Suggest enclosing format string with `""` under special cases)
 - rust-lang/rust#155707 (Fix minor panic-unsoundness in CString::clone_into)
 - rust-lang/rust#155719 (Suggest `.iter()` for shared projections)
 - rust-lang/rust#155779 (ssa_range_prop: use `if let` guards)
 - rust-lang/rust#155789 (Cleanups to `AttributeExt`)
 - rust-lang/rust#155805 (Mention `DEPRECATED_LLVM_INTRINSIC` lint for internal use)
 - rust-lang/rust#155806 (Remove the incomplete marker from `impl` restrictions)
 - rust-lang/rust#155820 (Avoid improper spans when `...` or `..=` is recovered from non-ASCII)
 - rust-lang/rust#155822 (Add default field values to diagnostic FormatArgs)
2026-04-26 20:31:33 +00:00
Jonathan Brouwer
139bcba8f6 Rollup merge of #155822 - mejrs:default_fmt_args, r=JonathanBrouwer
Add default field values to diagnostic FormatArgs

This type has a decent amount of unused fields (and I am planning to add more).
2026-04-26 19:06:32 +02:00
Jonathan Brouwer
ae7751677e Rollup merge of #155820 - Zalathar:range, r=Kivooeo
Avoid improper spans when `...` or `..=` is recovered from non-ASCII

- Fixes https://github.com/rust-lang/rust/issues/155799

Adjusting span endpoints by `BytePos(1)` is almost always bad news.

In this case, the code assumed that it was skipping over a single ASCII character. But in the presence of parser recovery from other non-ASCII characters this resulted in an ICE due to bad string indexing when emitting suggestions.
2026-04-26 19:06:31 +02:00
Jonathan Brouwer
b227d459be Rollup merge of #155806 - CoCo-Japan-pan:impl-restriction-mark-unstable, r=jhpratt,Urgau
Remove the incomplete marker from `impl` restrictions

Following the discussion on Zulip ([#gsoc > Idea: Implementing impl and mut restrictions @ 💬](https://rust-lang.zulipchat.com/#narrow/channel/421156-gsoc/topic/Idea.3A.20Implementing.20impl.20and.20mut.20restrictions/near/590562763)),this PR removes the incomplete marker from `#[feature(impl_restriction)]`.
Tracking issue for restrictions: rust-lang/rust#105077.

r? @Urgau
cc @jhpratt
2026-04-26 19:06:31 +02:00
Jonathan Brouwer
c96f7d2e53 Rollup merge of #155805 - shian15810:patch-1, r=mejrs
Mention `DEPRECATED_LLVM_INTRINSIC` lint for internal use

Since `link_llvm_intrinsics` is an internal feature, having `deprecated_llvm_intrinsic` lint appearing in https://doc.rust-lang.org/nightly/rustc/lints/listing/allowed-by-default.html#deprecated-llvm-intrinsic without mentioning its internal nature is quite confusing to the end users.

This PR improves the documentation of recently merged PR https://github.com/rust-lang/rust/pull/140763 that implemented `deprecated_llvm_intrinsic` lint by mentioning the internal nature of `deprecated_llvm_intrinsic` lint and `link_llvm_intrinsics` feature.

Tracking issue of unstable `link_llvm_intrinsics` feature: https://github.com/rust-lang/rust/issues/29602
2026-04-26 19:06:30 +02:00
Jonathan Brouwer
37b53a9461 Rollup merge of #155789 - JonathanBrouwer:attribute-ext, r=mejrs
Cleanups to `AttributeExt`

r? @mejrs

- Makes some functions take `ast::Attribute` instead of `impl AttributeExt`
- Remove `deprecation_note` from `AttributeExt`, since the two implementations are basically seperate
2026-04-26 19:06:29 +02:00
Jonathan Brouwer
ecdcd0e588 Rollup merge of #155779 - Human9000-bit:ssa-range-prop-ref, r=Kivooeo
ssa_range_prop: use `if let` guards

It is a bit cleaner this way

r? @dianqk
2026-04-26 19:06:29 +02:00
Jonathan Brouwer
59ca5ae02c Rollup merge of #155719 - qaijuang:suggest-iter-for-shared-projections-issue-155365, r=ShoyuVanilla
Suggest `.iter()` for shared projections

Fixes rust-lang/rust#155365.
2026-04-26 19:06:28 +02:00
Jonathan Brouwer
27aa1c5222 Rollup merge of #155707 - Manishearth:cstring-vuln, r=Mark-Simulacrum
Fix minor panic-unsoundness in CString::clone_into

`CString` must always contain a null byte, calling `mem::take` on its inner allocation puts it in an invalid state (causing UB if e.g. it hits `CString::drop`) that can be observed if the allocator panics.

Unfortunately, this solution allocates an intermediate 1-element `Box`. I'm not sure of a clean way to avoid that additional allocation; we could directly `realloc` if we want but it's tricky. Might be something we can do with `ManuallyDrop`.

I do have a gnarly miri test for this that uses a panicky allocator, but I'm not sure where it would go. Happy to push it up if someone has a suggestion.

Bug discovered by Rust Foundation Security using AI. I'm just helping with the patch as a member of wg-security-response. We do not believe this bug needs embargo, it is a soundness fix for hard-to-trigger unsoundness.
2026-04-26 19:06:28 +02:00
Jonathan Brouwer
fa16f8102e Rollup merge of #155693 - cclfmht:fix/issue-155508, r=ShoyuVanilla
Suggest enclosing format string with `""` under special cases

This commit adds suggestions on enclosing format string with `""` when it falls into the following 3 cases: `{}`, `{:?}`, `{:#?}` as mentioned in rust-lang/rust#155508.

Currently, this commit only recognizes the above 3 cases. I wonder if we should generalize this to more cases, for example, appying this suggestion to `Block`s with only 0 or 1 `Stmt`, such as `{:#x}`, `{:^10}`, `{abc}`.
2026-04-26 19:06:27 +02:00
Jonathan Brouwer
a722bc89a0 Rollup merge of #155823 - RalfJung:miri, r=RalfJung
miri subtree update

Subtree update of `miri` to f3f6dca488.

Created using https://github.com/rust-lang/josh-sync.

r? @ghost
2026-04-26 19:06:26 +02:00
Jonathan Brouwer
382ec81061 Rollup merge of #155757 - mejrs:ident_help, r=Kivooeo
macro_metavar_expr_concat: explain why idents are invalid

Recently I've been playing around with `macro_metavar_expr_concat` and in the process wasted more time than I'd have liked on debugging my dodgy idents. This should make that experience much nicer going forward.
2026-04-26 19:06:26 +02:00
bors
d4f7856569 Auto merge of #155473 - scottmcm:tweak_niche_assignment, r=chenyukang,mati865
Prefer `-1` for `None`



Currently we pick "weird" numbers like `1114112` for `None::<char>`.  While that's not *wrong*, it's kinda *unnatural* -- a human wouldn't make that choice.

This PR instead picks `-1` for thinge like `None::<char>` -- like [clang's `WEOF`](63ae74b78a/libc/include/llvm-libc-macros/wchar-macros.h (L15)) -- and `None::<bool>` and such.

Any enums with more than one niched value (so not `Result` nor `Option`) remain as they were before.  Also we continue to use `0` when that's possible -- `-1` is only preferred when zero *isn't* possible.

---

Inspired when someone in discord posted an example like this <https://rust.godbolt.org/z/W94s9qdYW> and I thought it was odd that we're currently picking `-9223372036854775808` to be the value to store to mark an `Option<Vec<_>>` as `None`.  (Especially since that needs an 8-byte immediate on x64, and writing `-1` is only a 4-byte immediate.)
2026-04-26 17:06:25 +00:00
Jonathan Brouwer
9170ff7733 Rollup merge of #155574 - bushrat011899:core_io_raw_os_error, r=Mark-Simulacrum
Move `std::io::RawOsError` to `core::io`

ACP: https://github.com/rust-lang/libs-team/issues/755
Tracking issue: https://github.com/rust-lang/rust/issues/154046
Related: https://github.com/rust-lang/rust/pull/154654

## Description

As a part of moving components of `std::io` into `alloc::io` and `core::io`, there will need to be a new home for the type `RawOsError`. In this PR, I propose moving it to `core::io`, and removing it from `std::sys`. I suspect this will be quite controversial as it is a platform dependent type, but this is not the only instance of a type being conditioned on `target_os` in `core` (e.g., `core::os` and `core::ffi`).

Since `RawOsError` is currently unstable, I think it's reasonable to make this move now, and worry about making it platform independent if/when it is stabilized (e.g., replacing it with a wrapper around `isize` on all platforms).

---

## Notes

* No AI tooling of any kind was used during the creation of this PR.
2026-04-26 19:06:25 +02:00
Jonathan Brouwer
eb779a151b Rollup merge of #155250 - ChrisDenton:pipe-fs, r=Mark-Simulacrum
Windows: Cache the pipe filesystem handle

Updates the anonymous pipe handling based on feedback from @lhecker  (see https://github.com/rust-lang/rust/pull/142517#discussion_r3065864262). This does two things:

1. Cache the handle to the pipe filesystem so we don't have to reopen it each time.
2. Use the `\Device\NamedPipe\` directly instead of the symlink to it.
2026-04-26 19:06:24 +02:00
Jonathan Brouwer
691ab1b396 Rollup merge of #153457 - dianne:no-coercing-in-pin-macro, r=Mark-Simulacrum,jackh726
prevent deref coercions in `pin!`

Mitigates rust-lang/rust#153438 using a (hopefully temporary!) typed macro idiom to ensure that when `pin!` produces a `Pin<&mut T>`, its argument is of type `T`. See https://github.com/rust-lang/rust/issues/153438#issuecomment-4006727101 for my ideas on how this could be changed in the future.
2026-04-26 19:06:24 +02:00
Jonathan Brouwer
7c71f48c5d Rollup merge of #152995 - asder8215:windows_permissions_ext, r=Mark-Simulacrum
ACP Implementation of PermissionsExt for Windows

This PR implements the `PermissionsExt` for Windows ACP and adds file attribute methods in `FilePermissions` struct (to be decided whether we use them or not). See this [tracking issue](https://github.com/rust-lang/rust/issues/152956#event-22976637690) for further detail and links.

I also added some comments in the code for clarifications about the ACP (e.g. whether we should have a `set_file_attributes()` + `from_file_attributes()` method to mirror what unix's `PermissionsExt` is doing).

Also, some relevant links on this:
* [File Attribute Constants](https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants)
* [`attrib` command](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/attrib)
* [SetFileAttributesA](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfileattributesa)
* [GetFileAttributesA](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileattributesa)
* [Window's File Attributes Column Values](https://superuser.com/questions/44812/windows-explorers-file-attribute-column-values)
* [What is the 'M' attribute in Windows file system for?](https://superuser.com/questions/1621649/what-is-the-m-attribute-in-windows-file-system-for)

Note: Apologies for the multiple forced push. I haven't set up my Windows VM up yet to compile and check the code, so I've been using the CI to help me with that.

r? @ChrisDenton
2026-04-26 19:06:23 +02:00
jyn
7151184b46 Add some debugging to rustc_session filename handling 2026-04-26 16:19:11 +00:00
jyn
d9e227e98a Fix broken logic in incremental_verify_ich_failed 2026-04-26 16:18:45 +00:00
Sasha Pourcelot
a7330f4897 rustc_attr_parsing: use a try {} in or_malformed 2026-04-26 15:15:25 +00:00
Qai Juang
28c079ae40 Suggest .iter() for shared projections
* Suggest `.iter()` for shared projections
* address few nits
* a few improvements
2026-04-26 14:30:46 +00:00
mejrs
48fe89f994 add default field values to diagnostic FormatArgs 2026-04-26 14:23:53 +02:00
Usman Akinyemi
a677828c48 Add boxing suggestions for return expressions in impl Trait functions
Signed-off-by: Usman Akinyemi <usmanakinyemi202@gmail.com>
2026-04-26 17:43:40 +05:30
Zalathar
9ceed255b5 Avoid improper spans when ... or ..= is recovered from non-ASCII
This avoids an ICE due to indexing into the middle of a multi-byte character.
2026-04-26 21:41:46 +10:00
Zalathar
f107bb85a2 Regression test for improper spans in inclusive-range suggestions 2026-04-26 21:36:51 +10:00
Ralf Jung
9ae47c9b53 Merge pull request #4812 from enthropy7/master
Support fstat on non-file-backed FDs
2026-04-26 11:23:07 +00:00
Jonathan Brouwer
163aedc873 Convert attribute FinalizeFn to fn pointer 2026-04-26 13:09:50 +02:00
Ralf Jung
c91a363db1 merge fstat and metadata functions 2026-04-26 12:59:02 +02:00
cclfmht
2c16f9edf5 Suggest enclosing format string with "" under special cases
* Suggest enclosing format string under special cases

This commit add suggestions about enclosing format string when it falls
into the following cases: `{}`, `{:?}`, `{:#?}`.
* Add HELP annotations in the UI test
2026-04-26 10:50:05 +00:00
Usman Akinyemi
4fc64f4180 Add boxing suggestions for impl Trait return type mismatches
Signed-off-by: Usman Akinyemi <usmanakinyemi202@gmail.com>
2026-04-26 14:58:49 +05:30
bors
c7fe5e9d1e Auto merge of #155813 - JonathanBrouwer:rollup-M9eCmdI, r=JonathanBrouwer
Rollup of 2 pull requests

Successful merges:

 - rust-lang/rust#155774 (std: maintain `CStringArray` null-termination even if `Vec::push` panics)
 - rust-lang/rust#155810 (Expand the initialism UCRT in rustc book)
2026-04-26 09:03:36 +00:00
Jonathan Brouwer
ea0a790fa5 Rollup merge of #155810 - miikkas:expand-acronym-ucrt, r=Noratrieb
Expand the initialism UCRT in rustc book

This PR adds a commit expanding the initialism UCRT on first use in the rusct book chapter on the [*-windows-gnullvm platform support](https://doc.rust-lang.org/nightly/rustc/platform-support/windows-gnullvm.html), making the chapter easier to understand. Microsoft, the originator of this technology (and thus, the canonical source for the acronym) in Windows, expands it to _Universal C Runtime_[^1][^2][^3]. The same expansion is added to the chapter.

[^1]: https://learn.microsoft.com/en-us/cpp/porting/upgrade-your-code-to-the-universal-crt
[^2]: https://learn.microsoft.com/en-us/cpp/windows/universal-crt-deployment
[^3]: https://devblogs.microsoft.com/cppblog/introducing-the-universal-crt/
2026-04-26 11:02:50 +02:00
Jonathan Brouwer
e9607db8ac Rollup merge of #155774 - joboet:cstring_array_null, r=jhpratt
std: maintain `CStringArray` null-termination even if `Vec::push` panics

Fixes rust-lang/rust#155748 by performing the `push` of the new null terminator before overwriting the previous one.
2026-04-26 11:02:49 +02:00
Miikka Salminen
33c1e869d7 Expand the initialism UCRT in rustc book
This commit expands the initialism UCRT on first use in the rusct book
chapter on the *-windows-gnullvm platform support, making the chapter
easier to understand. Microsoft, the originator of this technology in
Windows, expands it to Universal C Runtime[1]. The same expansion is
added to the chapter.

[1] https://learn.microsoft.com/en-us/cpp/porting/upgrade-your-code-to-the-universal-crt
2026-04-26 09:05:37 +03:00
CoCo-Japan-pan
79e10fd5ef Remove the incomplete marker from impl restrictions 2026-04-26 13:07:09 +09:00
Cheeshian Chuah
efaf460224 Mention DEPRECATED_LLVM_INTRINSIC lint for internal use 2026-04-26 11:05:05 +08:00
Scott McMurray
ba1a33e105 Prefer -1 for None
Currently we pick "weird" numbers like `1114112` for `None::<char>`.  While that's not *wrong*, it's kinda *unnatural* -- a human wouldn't make that choice.

This PR instead picks `-1` for thinge like `None::<char>` -- like clang's `WEOF` -- and `None::<bool>` and such.

Any enums with more than one niched value (so not `Result` nor `Option`) remain as they were before.
2026-04-25 14:57:23 -07:00
bors
68ffae46b5 Auto merge of #155796 - JonathanBrouwer:rollup-uKXw9ZB, r=JonathanBrouwer
Rollup of 9 pull requests

Successful merges:

 - rust-lang/rust#146181 (Add intrinsic for launch-sized workgroup memory on GPUs)
 - rust-lang/rust#154803 (Fix ICE from cfg_attr_trace )
 - rust-lang/rust#155065 (Error on invalid macho section specifier)
 - rust-lang/rust#155485 (Add an edge-case test for `--remap-path-prefix` for `rustc` & `rustdoc`)
 - rust-lang/rust#155659 (cleanup, restructure and merge `tests/ui/deriving` into `tests/ui/derives`)
 - rust-lang/rust#155676 ( Reject implementing const Drop for types that are not const `Destruct` already)
 - rust-lang/rust#155696 (Add a higher-level API for parsing attributes)
 - rust-lang/rust#155769 (triagebot.toml: Ping Enselic when tests/debuginfo/basic-stepping.rs changes)
 - rust-lang/rust#155783 (Do not suggest internal cfg trace attributes)
2026-04-25 21:08:31 +00:00
Jonathan Brouwer
3b59d9d58e Rollup merge of #155783 - qaijuang:issue-150566-cfg-trace-suggestions, r=JonathanBrouwer
Do not suggest internal cfg trace attributes

Fixes rust-lang/rust#150566.
2026-04-25 23:07:53 +02:00
Jonathan Brouwer
730b6766c6 Rollup merge of #155769 - Enselic:ping-enselic, r=Urgau
triagebot.toml: Ping Enselic when tests/debuginfo/basic-stepping.rs changes

The test `tests/debuginfo/basic-stepping.rs` has a history of [regressing for subtle reasons](https://github.com/rust-lang/rust/issues/33013#issuecomment-3121579216) ([retroactively](https://github.com/rust-lang/rust/pull/144497)), and has [expected behavior](https://github.com/rust-lang/rust/pull/153941) that is [not obvious](https://github.com/rust-lang/rust/pull/155377). So I'd like to keep an extra eye one it.
2026-04-25 23:07:53 +02:00
Jonathan Brouwer
97dd613234 Rollup merge of #155696 - scrabsha:push-kxqstpltlwzn, r=JonathanBrouwer
Add a higher-level API for parsing attributes
2026-04-25 23:07:52 +02:00
Jonathan Brouwer
2c639cc7fe Rollup merge of #155676 - oli-obk:const-drop-non-const-destruct, r=fee1-dead
Reject implementing const Drop for types that are not const `Destruct` already

fixes rust-lang/rust#155618

While there is no soundness or otherwise issue currently, this PR ensures that people get what they expect. It seems wrong to allow implementing `const Drop`, but then the type still can't be dropped at compile-time.

r? @fee1-dead
2026-04-25 23:07:51 +02:00
Jonathan Brouwer
0e9c586699 Rollup merge of #155659 - cyrgani:deriving-2, r=Kivooeo
cleanup, restructure and merge `tests/ui/deriving` into `tests/ui/derives`

As a followup to https://github.com/rust-lang/rust/pull/155615, this PR deletes some outdated tests from these directories, splits up `ui/derives` into smaller directories to roughly group tests by the derive macros they use and moves over all tests from `ui/deriving` into `ui/derives`.
r? @Kivooeo
2026-04-25 23:07:51 +02:00
Jonathan Brouwer
7050d618af Rollup merge of #155485 - Urgau:remap-edge-case-test, r=GuillaumeGomez
Add an edge-case test for `--remap-path-prefix` for `rustc` & `rustdoc`

Intended to resolve @lolbinarycat concern https://github.com/rust-lang/rust/pull/155307#issuecomment-4270904667
2026-04-25 23:07:50 +02:00
Jonathan Brouwer
1fe66ee46e Rollup merge of #155065 - folkertdev:macho-section-specifier, r=JonathanBrouwer
Error on invalid macho section specifier

The macho section specifier used by `#[link_section = "..."]` is more strict than e.g. the one for elf. LLVM will error when you get it wrong, which is easy to do if you're used to elf. So, provide some guidance for the simplest mistakes, based on the LLVM validation.

Currently compilation fails with an LLVM error, see https://godbolt.org/z/WoE8EdK1K.

The LLVM validation logic is at

a0f0d6342e/llvm/lib/MC/MCSectionMachO.cpp (L199-L203)

LLVM validates the other components of the section specifier too, but it feels a bit fragile to duplicate those checks. If you get that far, hopefully the LLVM errors will be sufficient to get unstuck.

---

sidequest from https://github.com/rust-lang/rust/pull/147811

r? JonathanBrouwer

specifically, is this the right place for this sort of validation? `rustc_attr_parsing` also does some validation.
2026-04-25 23:07:50 +02:00
Jonathan Brouwer
76a365523f Rollup merge of #154803 - chenyukang:yukang-fix-154801-cfg-attr-span, r=JonathanBrouwer
Fix ICE from cfg_attr_trace

Fixes rust-lang/rust#154801
Fixes https://github.com/rust-lang/rust/issues/143094

r? @JonathanBrouwer

The root cause is we recovery from parsing attribute error here:
ed6f9af7d4/compiler/rustc_attr_parsing/src/parser.rs (L550)
while the later suggestion code from type checking try to inspect the attr span of the `expr` in the second error, keep the span seems reasonable.
2026-04-25 23:07:49 +02:00
Jonathan Brouwer
dde4886801 Rollup merge of #146181 - Flakebi:dynamic-shared-memory, r=ZuseZ4,Sa4dus,workingjubilee,RalfJung,nikic,kjetilkjeka,kulst
Add intrinsic for launch-sized workgroup memory on GPUs

Workgroup memory is a memory region that is shared between all
threads in a workgroup on GPUs. Workgroup memory can be allocated
statically or after compilation, when launching a gpu-kernel.
The intrinsic added here returns the pointer to the memory that is
allocated at launch-time.

# Interface

With this change, workgroup memory can be accessed in Rust by
calling the new `gpu_launch_sized_workgroup_mem<T>() -> *mut T`
intrinsic.

It returns the pointer to workgroup memory guaranteeing that it is
aligned to at least the alignment of `T`.
The pointer is dereferencable for the size specified when launching the
current gpu-kernel (which may be the size of `T` but can also be larger
or smaller or zero).

All calls to this intrinsic return a pointer to the same address.

See the intrinsic documentation for more details.

## Alternative Interfaces

It was also considered to expose dynamic workgroup memory as extern
static variables in Rust, like they are represented in LLVM IR.
However, due to the pointer not being guaranteed to be dereferencable
(that depends on the allocated size at runtime), such a global must be
zero-sized, which makes global variables a bad fit.

# Implementation Details

Workgroup memory in amdgpu and nvptx lives in address space 3.
Workgroup memory from a launch is implemented by creating an
external global variable in address space 3. The global is declared with
size 0, as the actual size is only known at runtime. It is defined
behavior in LLVM to access an external global outside the defined size.

There is no similar way to get the allocated size of launch-sized
workgroup memory on amdgpu an nvptx, so users have to pass this
out-of-band or rely on target specific ways for now.

Tracking issue: rust-lang/rust#135516
2026-04-25 23:07:48 +02:00
Scott McMurray
9bc1313507 Add dump_layout tests for options of bool and char 2026-04-25 13:46:42 -07:00
Jonathan Brouwer
e3b0e9db08 Remove deprecation_note from AttributeExt 2026-04-25 21:26:00 +02:00
Jonathan Brouwer
f113540cec Remove unnecessary uses of AttributeExt 2026-04-25 21:25:43 +02:00
Oli Scherer
7dcedafff2 Reject implementing const Drop for types that are not const Destruct already 2026-04-25 20:56:32 +02:00
Oli Scherer
642ee63c22 Add regression test 2026-04-25 20:55:51 +02:00
Folkert de Vries
a4f5c6e971 error on invalid macho section specifier 2026-04-25 20:06:30 +02:00
mejrs
b6c6dd1fa0 macro_metavar_expr_concat: explain why idents are invalid 2026-04-25 19:56:05 +02:00
bors
9838411cb7 Auto merge of #155257 - petrochenkov:visatleast, r=adwinwhite
privacy: Assert that compared visibilities are (usually) ordered



And make "greater than" (`>`) the new primary operation for comparing visibilities instead of "is at least" (`>=`).
2026-04-25 16:15:55 +00:00
Qai Juang
b17822575c Do not suggest internal cfg trace attributes 2026-04-25 11:47:34 -04:00
human9000
29d58f8b4c Utilize if let guards where aproppriate 2026-04-25 19:42:57 +05:00
Kevin Heavey
5cd9d929a9 Avoid Vec allocation in TyCtxt::mk_place_elem
`mk_place_elem` appends a single `PlaceElem` to an existing (interned)
projection. The current implementation copies the projection into a
fresh `Vec`, pushes the new element, and re-interns the slice, which
allocates on the heap on every call.

Feed the elements through `mk_place_elems_from_iter` so that
`CollectAndApply`'s hand-unrolled stack fast path (up to 9 elements,
in `rustc_type_ir::interner`) kicks in for the common case of short
projections and the `Vec` allocation is skipped entirely. The behavior
is identical for longer projections (the fast path falls back to a
`Vec` internally).
2026-04-25 15:05:59 +01:00
joboet
bab4983f6c std: maintain CStringArray null-termination even if Vec::push panics 2026-04-25 15:17:36 +02:00
bors
fb76025f2f Auto merge of #155460 - cjgillot:unmut-resolver-ast, r=oli-obk
Do not modify resolver outputs during lowering



Split from https://github.com/rust-lang/rust/pull/142830

I believe this achieves the same thing as https://github.com/rust-lang/rust/pull/153656 but in a much simpler way. 

This PR forces AST->HIR lowering to stop mutating resolver outputs. Instead, it manages a few override maps that only live during lowering and are dropped afterwards.

r? @petrochenkov 
cc @aerooneqq
2026-04-25 10:01:32 +00:00
yukang
5e00484c38 Avoid misleading closure return type note 2026-04-25 16:27:05 +08:00
Martin Nordholts
ff73b8ac2b triagebot.toml: Ping Enselic when tests/debuginfo/basic-stepping.rs changes
The test `tests/debuginfo/basic-stepping.rs` has a history of regressing
for subtle reasons, and has non-obvious expectations. So I'd like to
keep an extra eye on it.
2026-04-25 10:11:10 +02:00
bors
7e0430fafc Auto merge of #155766 - jhpratt:rollup-EcXAaqS, r=jhpratt
Rollup of 7 pull requests

Successful merges:

 - rust-lang/rust#155643 (Improve suggestion for $-prefixed fragment specifiers)
 - rust-lang/rust#154197 (Avoid redundant clone suggestions in borrowck diagnostics)
 - rust-lang/rust#154372 (Exposing Float Masks)
 - rust-lang/rust#155680 (Handle index projections in call destinations in DSE)
 - rust-lang/rust#155732 (bootstrap: Don't clone submodules unconditionally in dry-run)
 - rust-lang/rust#155737 (Account for `GetSyntheticValue` failures)
 - rust-lang/rust#155738 (Pass fields to `is_tuple_fields` instead of `SBValue` object)
2026-04-25 06:41:56 +00:00
Jacob Pratt
84fd561f22 Rollup merge of #155738 - Walnut356:tuple_fields, r=jieyouxu
Pass fields to `is_tuple_fields` instead of `SBValue` object

straightforward fix for a logic error. `is_tuple_fields` expects a `list`, so we pass that in instead of the value object.

Coincidentally, this also fixes one of the 3 DI tests that fails on `x86_64-pc-windows-gnu` (`tests/debuginfo/union-smoke.rs`)
2026-04-25 01:21:54 -04:00
Jacob Pratt
0c27f91e04 Rollup merge of #155737 - Walnut356:getsyntheticvalue, r=jieyouxu
Account for `GetSyntheticValue` failures

`GetSyntheticValue` returns an invalid `SBValue` if no synthetic is present. That wasn't a problem before when we  were attaching synthetics to every type, but it won't be the case once github.com/rust-lang/rust/pull/155336 or similar lands. Additionally, codelldb subverts `lldb_commands` to apply similar behavior that doesn't attach synthetics to every type, so this fixes a regression there too.

Additionally, I removed 1 useless instance of `GetSyntheticValue`, since pointers should always be `IndirectionSyntheticProvider`, not `DefaultSyntheticProvider`.
2026-04-25 01:21:54 -04:00
Jacob Pratt
780e699707 Rollup merge of #155732 - ferrocene:jyn/dry-run, r=jieyouxu
bootstrap: Don't clone submodules unconditionally in dry-run

This made it very annoying to debug bootstrap itself, because every `--dry-run` invocation would start out by cloning LLVM, which is almost never necessary. Instead change a few Steps to properly support dry_run when no submodule is checked out.

I tested this by running all of `check`, `build`, `doc`, `dist`, `install`, `vendor`, `clippy`, `fix`, and `miri` with `--dry-run`.
2026-04-25 01:21:53 -04:00
Jacob Pratt
fa82155e54 Rollup merge of #155680 - Amanieu:call-arg-move-index, r=cjgillot
Handle index projections in call destinations in DSE

Since call destinations are evaluated after call arguments, we can't turn copy arguments into moves if the same local is later used as an index projection in the call destination.

DSE call arg optimization: rust-lang/rust#113758

r? @cjgillot
cc @RalfJung
2026-04-25 01:21:52 -04:00
Jacob Pratt
b3ccc964d5 Rollup merge of #154372 - Apersoma:float_masks, r=tgross35
Exposing Float Masks

Tracking issue: rust-lang/rust#154064
ACP: rust-lang/libs-team#753
2026-04-25 01:21:52 -04:00
Jacob Pratt
0af72af1b8 Rollup merge of #154197 - yuk1ty:fix-redundant-clone-error2, r=adwinwhite
Avoid redundant clone suggestions in borrowck diagnostics

Fixes rust-lang/rust#153886

Removed redundant `.clone()` suggestions.

I found that there are two patterns to handle this issue while I was implementing:

- Should suggest only UFCS
- Should suggest only simple `.clone()`

For the target issue, we can just remove the UFCS (`<Option<String> as Clone>::clone(&selection.1)`) side.

However, for the `BorrowedContentSource::OverloadedDeref` pattern like `Rc<Vec<i32>>`, for instance the `borrowck-move-out-of-overloaded-auto-deref.rs` test case, I think we need to employ the UFCS way. The actual test case is:

```rust
//@ run-rustfix
use std::rc::Rc;

pub fn main() {
    let _x = Rc::new(vec![1, 2]).into_iter();
    //~^ ERROR [E0507]
}
```

And another error will be shown if we simply use the simple `.clone()` pattern. Like:

```rust
use std::rc::Rc;

pub fn main() {
    let _x = Rc::new(vec![1, 2]).clone().into_iter();
}
```

then we will get

```
error[E0507]: cannot move out of an `Rc`
   --> src/main.rs:5:14
    |
  5 |     let _x = Rc::new(vec![1, 2]).clone().into_iter();
    |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ----------- value moved due to this method call
    |              |
    |              move occurs because value has type `Vec<i32>`, which does not implement the `Copy` trait
    |
note: `into_iter` takes ownership of the receiver `self`, which moves value
   --> /playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/collect.rs:310:18
    |
310 |     fn into_iter(self) -> Self::IntoIter;
    |                  ^^^^
help: you can `clone` the value and consume it, but this might not be your desired behavior
    |
  5 -     let _x = Rc::new(vec![1, 2]).clone().into_iter();
  5 +     let _x = <Vec<i32> as Clone>::clone(&Rc::new(vec![1, 2])).into_iter();
    |

For more information about this error, try `rustc --explain E0507`.
```

[Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=7e767bed3f1c573c03642f20f454ed03)

In this case, `Rc::clone` only increments the reference count and returns a new `Rc<Vec<i32>>`; it does not grant ownership of the inner `Vec<i32>`. As a result, calling into_iter() attempts to move the `Vec<i32>`, leading to the same E0507 error again.

On the other hand, in UFCS form:

```
<Vec<i32> as Clone>::clone(&Rc::new(vec![1, 2])).into_iter()
```

This explicitly calls `<Vec<i32> as Clone>::clone`, and the argument `&Rc<Vec<i32>>` is treated as `&Vec<i32>` via Rc’s `Deref` implementation. As a result, the `Vec<i32>` itself is cloned, yielding an owned `Vec<i32>`, which allows `into_iter()` to succeed, if my understanding is correct.

I addressed the issue as far as I could find the edge cases but please advice me if I'm overlooking something.
2026-04-25 01:21:51 -04:00
Jacob Pratt
d3eddcff9e Rollup merge of #155643 - qaijuang:fix-macro-missing-fragment-dollar-suggestion, r=eholk
Improve suggestion for $-prefixed fragment specifiers

Fixes rust-lang/rust#155505
2026-04-25 01:21:50 -04:00
bors
0a4ee3f74b Auto merge of #155756 - weihanglo:update-cargo, r=weihanglo
Update cargo submodule

10 commits in 06ac0e7c05770a8c7bbf67bdd12fa1a1eefdc8ae..eb9b60f1f6604b5e022c56be31692c215b8ba11d
2026-04-21 15:33:56 +0000 to 2026-04-24 20:52:07 +0000
- chore: Remove unused deps (rust-lang/cargo#16938)
- feat(compile): Stabilize `build.warnings` (rust-lang/cargo#16796)
- cargo clean: do not error if explicitly specified target-dir does not exist (rust-lang/cargo#16934)
- Revert "feat(lints): Add unused deps ignore list" (rust-lang/cargo#16937)
- fix(compile): Ignore unused deps if also transitive  (rust-lang/cargo#16935)
- Update rustls (rust-lang/cargo#16932)
- chore(deps): update rust crate openssl to v0.10.78 [security] (rust-lang/cargo#16931)
- chore(build-rs): Ensure we lint the crate (rust-lang/cargo#16930)
- Fix flaky test: proc_macro_in_artifact_dep (rust-lang/cargo#16922)
- refactor(compile): Log all ignored unused externs (rust-lang/cargo#16920)

r? ghost
2026-04-25 03:28:50 +00:00
yukang
45b4e3c52b Fix ICE of trying to get span from all attrs 2026-04-25 11:11:23 +08:00
bors
597d9e43be Auto merge of #155755 - JonathanBrouwer:rollup-oG1Wz3V, r=JonathanBrouwer
Rollup of 3 pull requests

Successful merges:

 - rust-lang/rust#155754 (make the `core::ffi::va_list` module private)
 - rust-lang/rust#155522 (cmse: test returning `MaybeUninit<T>`)
 - rust-lang/rust#155741 (std: Refactor BufWriter::flush to use the `?` operator)
2026-04-25 00:13:26 +00:00
Camille Gillot
4433512e90 Lighten and document partial_res_overrides. 2026-04-24 23:58:52 +00:00
Camille Gillot
9044aba8e1 Use imported NodeId. 2026-04-24 23:58:52 +00:00
Camille Gillot
0705bbac94 Do not modify resolver outputs during lowering
Co-authored-by: Camille Gillot <gillot.camille@gmail.com>
2026-04-24 23:58:52 +00:00
yuk1ty
61ff157bd4 Address custom type implementing Derefs to suggest UFCS clone 2026-04-25 08:46:06 +09:00
Apersoma
d5b941d163 added float masks feature 2026-04-24 23:06:04 +00:00
Jonathan Brouwer
6f536cf8f4 Rollup merge of #155741 - xtqqczze:question-mark-bufwriter-flush, r=WaffleLapkin
std: Refactor BufWriter::flush to use the `?` operator

Functionally, this is equivalent and may     be slightly more amenable to inlining.
2026-04-25 00:08:11 +02:00
Jonathan Brouwer
39d84243b2 Rollup merge of #155522 - folkertdev:cmse-test-maybe-uninit, r=WaffleLapkin
cmse: test returning `MaybeUninit<T>`

tracking issue: https://github.com/rust-lang/rust/issues/81391
tracking issue: https://github.com/rust-lang/rust/issues/75835

Some tests from https://github.com/rust-lang/rust/pull/147697 that already work and are useful. Extracting them shrinks that (currently blocked) PR.

The code in `tests/ui/cmse-nonsecure/cmse-nonsecure-call/return-via-stack.rs` checks that `MaybeUninit<T>` is considered abi-compatible with `T`. The code in `tests/ui/cmse-nonsecure/cmse-nonsecure-entry/params-via-stack.rs` really only tests that no errors/warnings are emitted.

r? davidtwco
2026-04-25 00:08:10 +02:00
Jonathan Brouwer
6d6b99eab2 Rollup merge of #155754 - folkertdev:hide-core-ffi-va-list, r=tgross35
make the `core::ffi::va_list` module private

tracking issue: https://github.com/rust-lang/rust/issues/44930

the types are exported from `core::ffi` itself.

T-libs-api decided that we should only export the types from `core::ffi`, and should not make `core::ffi::va_list` public, see https://github.com/rust-lang/rust/issues/44930#issuecomment-4289951633.

r? tgross35
2026-04-25 00:08:09 +02:00
Weihang Lo
d439d07af2 Update cargo submodule 2026-04-24 17:43:12 -04:00
bors
80729d7ce0 Auto merge of #155662 - mejrs:this_the_thing, r=petrochenkov
Permit `{This}` in diagnostic attribute format literals

My motivation was that yesterday I wanted to write something like this and reference `$name` in the string literal.

```rust
pub mod sym {
   // stuff here
}

macro_rules! my_macro {
    ($name:ident $(,)?) => {{
        #[diagnostic::on_unknown(
            message = "this is not present in symbol table",
            note = "you must add it to rustc_span::symbol::symbol!"
        )]
        use sym::$name as name;
        // ...
    }}
}
```

That is (as far as I can tell) impossible or at least very unergonomic. This adds the ability to just reference the name of the item the attribute is on. I imagine that's useful for use inside macros generally, so it's also added for some other attributes.

The affected attributes are all unstable, it is not implemented for diagnostic::on_unimplemented (will do in its own PR).

Note that `{This}` is already usable in `#[rustc_on_unimplemented]`, so this does not implement it but just enables some more.

This PR also migrates one lint away from AttributeLintKind, and improves the messages for that lint.
2026-04-24 20:46:55 +00:00
Folkert de Vries
3851c60cf8 make the core::ffi::va_list module private
the types are exported from `core::ffi` itself
2026-04-24 22:18:22 +02:00
Qai Juang
2b46d9204a Improve suggestion for $-prefixed fragment specifiers 2026-04-24 14:59:01 -04:00
mejrs
c2916be8d7 Permit {This} in diagnostic attribute format literals 2026-04-24 19:59:32 +02:00
bors
7c61a357e3 Auto merge of #155745 - JonathanBrouwer:rollup-D6OSAOt, r=JonathanBrouwer
Rollup of 12 pull requests

Successful merges:

 - rust-lang/rust#149452 (Refactor out common code into a `IndexItem::new` constructor)
 - rust-lang/rust#155621 (Document #[diagnostic::on_move] in the unstable book.)
 - rust-lang/rust#155635 (delegation: rename `Self` generic param to `This` in recursive delegations)
 - rust-lang/rust#155730 (Some cleanups around per parent disambiguators)
 - rust-lang/rust#153537 (rustc_codegen_ssa: Define ELF flag value for sparc-unknown-linux-gnu)
 - rust-lang/rust#155219 (Do not suggest borrowing enclosing calls for nested where-clause obligations)
 - rust-lang/rust#155408 (rustdoc: Fix Managarm C Library name in cfg pretty printer)
 - rust-lang/rust#155571 (Enable AddressSanitizer on arm-unknown-linux-gnueabihf and armv7-unknown-linux-gnueabihf)
 - rust-lang/rust#155713 (test: Add a regression test for Apple platforms aborting on `free`)
 - rust-lang/rust#155723 (Fix tier level for 5 thumb bare-metal ARM targets)
 - rust-lang/rust#155735 (Fix typo by removing extra 'to')
 - rust-lang/rust#155736 (Remove `AllVariants` workaround for rust-analyzer)
2026-04-24 17:30:32 +00:00
enthropy7
058a8b9fa1 Support fstat on non-file-backed FDs 2026-04-24 20:02:41 +03:00
Jonathan Brouwer
2a885bb586 Rollup merge of #155736 - makai410:rm-ra-workaround, r=petrochenkov
Remove `AllVariants` workaround for rust-analyzer

Part of https://github.com/rust-lang/rust/issues/155677

Removes the `ALL_VARIANTS` alias added to work around rust-analyzer not supporting `#![feature(macro_derive)]`, which has since been fixed (rust-lang/rust-analyzer/issues/21043).
2026-04-24 18:19:21 +02:00
Jonathan Brouwer
4eaa44b4a8 Rollup merge of #155735 - Muhtasim-Rasheed:issue-155695-fix-typo, r=wesleywiser
Fix typo by removing extra 'to'

Fixes rust-lang/rust#155695

Fix a typo in the `std::convert` module documentation by removing an extra "to" in the module-level docs.
2026-04-24 18:19:21 +02:00
Jonathan Brouwer
75234e5d66 Rollup merge of #155723 - cezarbbb:fix-thumb-target-tier-spec, r=wesleywiser
Fix tier level for 5 thumb bare-metal ARM targets

The spec files for 5 Thumb-mode bare-metal ARM targets incorrectly set tier: Some(2), while the documentation correctly lists them as Tier 3. This mismatch was introduced in PR #150556 — the intent was Tier 2 eventually, but these targets should sit at Tier 3 until a proper Tier 3 → Tier 2 promotion MCP is submitted and approved.

This PR changes tier: Some(2) → Some(3) in the following spec files, making them consistent with the docs:

thumbv7a-none-eabi
thumbv7a-none-eabihf
thumbv7r-none-eabi
thumbv7r-none-eabihf
thumbv8r-none-eabihf

PS: No doc changes needed — they already correctly state Tier 3.

r?
2026-04-24 18:19:20 +02:00
Jonathan Brouwer
3ad0c706e6 Rollup merge of #155713 - tgross35:150898-regression-test, r=dianqk
test: Add a regression test for Apple platforms aborting on `free`

Add a regression test for https://github.com/rust-lang/rust/issues/150898 to make users aware that if this test failures, they may encounter unusual behavior elsewhere.
2026-04-24 18:19:19 +02:00
Jonathan Brouwer
396f99fcee Rollup merge of #155571 - chrisburel:asan-armv7, r=wesleywiser
Enable AddressSanitizer on arm-unknown-linux-gnueabihf and armv7-unknown-linux-gnueabihf

Add SanitizerSet::ADDRESS to the supported_sanitizers for the arm-unknown-linux-gnueabihf and armv7-unknown-linux-gnueabihf targets.

The AddressSanitizer is already enabled on the armv7-linux-androideabi platform, which shares the same ARM architecture. There is no reason these Linux GNU targets should not also support it, as the underlying LLVM support for ASan on 32-bit ARM is already in place.
2026-04-24 18:19:19 +02:00
Jonathan Brouwer
39d5d45b9a Rollup merge of #155408 - teor2345:rustdoc-env-names, r=lolbinarycat
rustdoc: Fix Managarm C Library name in cfg pretty printer

Like rust-lang/rust#155293, this was introduced in https://github.com/rust-lang/rust/pull/154328.

Unlike that PR, I don't think there's any need to backport, because this cfg is not used anywhere in the standard library.
(I searched for `"mlibc"`, the only place it's used in rust-lang/rust is the HTML doc test.)

#### Other Minor Fixes

Remove a FIXME comment in the pretty printer, `os = "none"` is always bare metal:
d227e48c56/compiler/rustc_target/src/spec/mod.rs (L3179)

Fix a comment typo, ignore another typo in vendored sources.
2026-04-24 18:19:18 +02:00
Jonathan Brouwer
a51a163574 Rollup merge of #155219 - nataliakokoromyti:fix-155088-borrow-suggestion-v2, r=JohnTitor
Do not suggest borrowing enclosing calls for nested where-clause obligations

In rust-lang/rust#155088, the compiler was blaming the whole call expr instead of the value that  actually failed the trait bound, so for foo(&[String::from("a")]) it was suggesting stuff like &foo(...). I changed the suggestion logic so it only emits borrow help if the expr it found actually matches the failed self type,  and used the same check for the “similar impl exists” help too. So now the compiler should give the normal error + required bound note.

Fix rust-lang/rust#155088
2026-04-24 18:19:17 +02:00
Jonathan Brouwer
08571af24d Rollup merge of #153537 - taiki-e:ef-sparc-32plus, r=wesleywiser
rustc_codegen_ssa: Define ELF flag value for sparc-unknown-linux-gnu

Currently, attempting to build this target using Ubuntu/Debian's sparc64-multilib toolchain results in the following link error ([full log](https://github.com/taiki-e/atomic-maybe-uninit/actions/runs/22798868888/job/66137493862#step:15:442)):

```
  = note: /usr/lib/gcc-cross/sparc64-linux-gnu/13/../../../../sparc64-linux-gnu/bin/ld: unknown architecture of input file `/home/runner/work/atomic-maybe-uninit/atomic-maybe-uninit/target/sparc-unknown-linux-gnu/debug/deps/rustcYzaDYW/symbols.o' is incompatible with sparc:v8plus output
```

This appears to be caused by the required e_flag being missing and can be fixed by setting `EF_SPARC_32PLUS`.

Tested using rustc with this patch applied and qemu-user (57d7e7f990, [log](https://github.com/taiki-e/atomic-maybe-uninit/actions/runs/22798793270/job/66137298093)).

Related discussion: https://github.com/rust-lang/rust/pull/131222#issuecomment-2393473488

r? workingjubilee
cc @glaubitz

@rustbot label +O-SPARC
2026-04-24 18:19:16 +02:00
Jonathan Brouwer
bbdfe217d4 Rollup merge of #155730 - oli-obk:cleanups, r=petrochenkov
Some cleanups around per parent disambiguators

r? @petrochenkov

follow-up to rust-lang/rust#155547

The two remaining uses are

* resolve_bound_vars, where it is a reasonable way to do it instead of having another field in the visitor that needs to get scoped (set & reset) every time we visit an opaque type. May still change that at some point, but it's not really an issue
* `create_def` in the resolver: will get removed together with my other refactorings for `node_id_to_def_id` (making that per-owner)
2026-04-24 18:19:16 +02:00
Jonathan Brouwer
ef162a52dc Rollup merge of #155635 - aerooneqq:delegation-generics-Self-rename, r=petrochenkov
delegation: rename `Self` generic param to `This` in recursive delegations

This PR supports renaming of `Self` generic parameter to `This` in recursive delegations scenario, this allows propagation of `This` as we rely on `Self` naming to check whether it is implicit Self of a trait. Comment with a bit deeper explanation is in `uplift_delegation_generic_params`. Part of rust-lang/rust#118212.

r? @petrochenkov
2026-04-24 18:19:15 +02:00
Jonathan Brouwer
e873839964 Rollup merge of #155621 - mejrs:document_diagnostic_on_move, r=chenyukang
Document #[diagnostic::on_move] in the unstable book.

Also adds the attribute on `std::fs::File` to stay consistent with the prose in the unstable book entry.

cc @estebank @rperier

Rendered:
<img width="791" height="903" alt="image" src="https://github.com/user-attachments/assets/a27a5211-7717-4f7f-a514-8316dccc78d5" />
<img width="779" height="390" alt="image" src="https://github.com/user-attachments/assets/a983108d-575e-4551-ab14-28611344e9b0" />
2026-04-24 18:19:14 +02:00
Jonathan Brouwer
d4a700a52b Rollup merge of #149452 - yotamofek:pr/rustdoc/IndexItem-new, r=notriddle,lolbinarycat
Refactor out common code into a `IndexItem::new` constructor

rust-lang/rust#149404
2026-04-24 18:19:13 +02:00
Ralf Jung
d4ca795f50 Merge pull request #4962 from elichai/elichai/_mm512_permutexvar_epi64
Implement `_mm512_permutexvar_epi64` shim
2026-04-24 15:47:58 +00:00
Sasha Pourcelot
067ef3df9c Add documentation for higher-level attribute parsing API 2026-04-24 15:33:15 +00:00
Sasha Pourcelot
9aa431c046 Add a simpler, harder to misuse, attribute parsing API 2026-04-24 15:33:15 +00:00
xtqqczze
15e60ebe6e std: Refactor flush method in BufWriter to use the ? operator 2026-04-24 15:19:36 +01:00
Walnut
180bfeffdb Pass fields to is_tuple_fields instead of SBValue object 2026-04-24 09:08:05 -05:00
yuk1ty
f69946ac64 Avoid redundant clone suggestions in borrowck diagnostics 2026-04-24 23:00:28 +09:00
Walnut
84ebb2269e account for GetSyntheticValue failures 2026-04-24 08:56:09 -05:00
bors
acb65f36a0 Auto merge of #155645 - dianqk:update-llvm, r=nikic
Update LLVM to 22.1.4

Unlocks https://github.com/rust-lang/rust/pull/155249.

I made a new branch that removes CI checks for macOS and reverts 24b53fbc67.
2026-04-24 13:55:36 +00:00
Makai
ece632c9f7 Remove AllVariants workaround for rust-analyzer 2026-04-24 21:25:20 +08:00
Muhtasim-Rasheed
52b93e04f8 Fix typo by removing extra 'to' 2026-04-24 18:18:08 +06:00
Jynn Nelson
bbdc7c4cc5 bootstrap: Don't clone submodules unconditionally in dry-run
This made it very annoying to debug bootstrap itself, because every
`--dry-run` invocation would start out by cloning LLVM, which is almost
never necessary. Instead change a few Steps to properly support dry_run
when no submodule is checked out.
2026-04-24 14:02:22 +02:00
Oli Scherer
bfb085da9f All generated associated types for opaque types in traits/impls have the same parent 2026-04-24 12:55:11 +02:00
Oli Scherer
e90878b9f2 All nested statics in a single interning run have the same parent
So we do not need to disambiguate considering parents
2026-04-24 12:45:55 +02:00
bors
ec6f9a5b44 Auto merge of #155709 - tgross35:compiler-builtins-sync-2026-04-22, r=tgross35
compiler-builtins subtree update

Subtree update of `compiler-builtins` to 4d3ab8695d.

Created using https://github.com/rust-lang/josh-sync.

Closes: https://github.com/rust-lang/rust/pull/155653
2026-04-24 10:39:25 +00:00
Trevor Gross
150905c3de test: Add a regression test for Apple platforms aborting on free
Add a regression test for RUST-150898 to make users aware that if this
test fails, they may encounter unusual behavior elsewhere.

Original repro authored by dianqk.
2026-04-24 05:33:03 -04:00
Flakebi
13ec3de673 Add intrinsic for launch-sized workgroup memory on GPUs
Workgroup memory is a memory region that is shared between all
threads in a workgroup on GPUs. Workgroup memory can be allocated
statically or after compilation, when launching a gpu-kernel.
The intrinsic added here returns the pointer to the memory that is
allocated at launch-time.

# Interface

With this change, workgroup memory can be accessed in Rust by
calling the new `gpu_launch_sized_workgroup_mem<T>() -> *mut T`
intrinsic.

It returns the pointer to workgroup memory guaranteeing that it is
aligned to at least the alignment of `T`.
The pointer is dereferencable for the size specified when launching the
current gpu-kernel (which may be the size of `T` but can also be larger
or smaller or zero).

All calls to this intrinsic return a pointer to the same address.

See the intrinsic documentation for more details.

## Alternative Interfaces

It was also considered to expose dynamic workgroup memory as extern
static variables in Rust, like they are represented in LLVM IR.
However, due to the pointer not being guaranteed to be dereferencable
(that depends on the allocated size at runtime), such a global must be
zero-sized, which makes global variables a bad fit.

# Implementation Details

Workgroup memory in amdgpu and nvptx lives in address space 3.
Workgroup memory from a launch is implemented by creating an
external global variable in address space 3. The global is declared with
size 0, as the actual size is only known at runtime. It is defined
behavior in LLVM to access an external global outside the defined size.

There is no similar way to get the allocated size of launch-sized
workgroup memory on amdgpu an nvptx, so users have to pass this
out-of-band or rely on target specific ways for now.
2026-04-24 10:03:45 +02:00
cezarbbb
27e12b89b7 Fix tier level for 5 thumb bare-metal ARM targets 2026-04-24 15:52:21 +08:00
bors
cf79d034aa Auto merge of #155720 - jhpratt:rollup-OEB9tQ5, r=jhpratt
Rollup of 9 pull requests

Successful merges:

 - rust-lang/rust#155684 (Generalize IO Traits for `Arc<T>` where `&T: IoTrait`)
 - rust-lang/rust#155081 (Move and clean up some ui test)
 - rust-lang/rust#155379 (Avoid query cycles in DataflowConstProp)
 - rust-lang/rust#155663 (Eliminate `CrateMetadataRef`.)
 - rust-lang/rust#155669 (Add `Sender` diagnostic item for `std::sync::mpsc::Sender`)
 - rust-lang/rust#155698 (Syntactically reject tuple index shorthands in struct patterns to fix a correctness regression)
 - rust-lang/rust#155703 (Remove myself as a maintainer of `wasm32-wasip1-threads`)
 - rust-lang/rust#155706 (Remove `AttributeLintKind` variants - part 7)
 - rust-lang/rust#155712 (Forbid `*-pass` and `*-fail` directives in tests/crashes)
2026-04-24 07:16:24 +00:00
aerooneqq
7f2a98d1fc Rename Self generic param to This in recursive delegations 2026-04-24 09:59:20 +03:00
Jacob Pratt
a2622ef238 Rollup merge of #155712 - Zalathar:crashes, r=jieyouxu
Forbid `*-pass` and `*-fail` directives in tests/crashes

Crash tests are always expected to crash during compilation, so there is no sensible meaning for specifying a pass expectation or a run-fail expectation in a crash test.

It could conceivably be useful to use failure expectations to specify whether a crash test requires codegen in order to crash, but currently none of the crash tests try to do that. If that functionality is desired in the future, we can always look into re-adding it after the internals of pass/fail expectations have been cleaned up a bit.

---

After this change, pass/fail directives are only allowed in UI tests, which should make it easier to overhaul and simplify their implementation.

r? jieyouxu
2026-04-24 02:42:54 -04:00
Jacob Pratt
87c27a9322 Rollup merge of #155706 - GuillaumeGomez:rm-attributelintkind, r=JonathanBrouwer
Remove `AttributeLintKind` variants - part 7

Part of https://github.com/rust-lang/rust/issues/153099.

It's the last easy one. Next one will require to get the crate name and to pass `Session` to the remaining lints. Fun times ahead. :)

r? @JonathanBrouwer
2026-04-24 02:42:53 -04:00
Jacob Pratt
71275054ed Rollup merge of #155703 - alexcrichton:remove-myself-from-wasm32-wasip1-threads, r=jieyouxu
Remove myself as a maintainer of `wasm32-wasip1-threads`

Over time the landscape for myself has changed, and I no longer would like to be officially listed as a maintainer of this target in Rust, so I'm going to step down. There are still a number of others listed on this target, however, so I'm sure they can address issues should they come up.
2026-04-24 02:42:53 -04:00
Jacob Pratt
1230f74ad5 Rollup merge of #155698 - fmease:no-struct-pat-tuple-index-shorthand, r=mu001999
Syntactically reject tuple index shorthands in struct patterns to fix a correctness regression

Split out of PR rust-lang/rust#154492. This fixes a correctness regression introduced in PR rust-lang/rust#81235 from 2021. Crater was run in my other PR and didn't report any real regressions (https://github.com/rust-lang/rust/pull/154492#issuecomment-4187544786); a rerun has been issued for a few spurious builds (https://github.com/rust-lang/rust/pull/154492#issuecomment-4237077272) but I'm certain it won't find anything either.

This is a theoretical breaking change that doesn't need any T-lang input IMHO since it's such a minute, niche and crystal clear bug that's not worth bothering them with (such a decision is not unprecedented). I'm adding it to the compatibility section of the release notes as is customary.

The Reference doesn't need updating since it didn't adopt this bug and thus accurately describes this part of the grammar as it used to be before 2021-02-23 and as it's meant to be.

The majority of the diff is doc comment additions & necessary UI test restructurings.
2026-04-24 02:42:52 -04:00
Jacob Pratt
46362de036 Rollup merge of #155669 - cammeresi:20260422-sender-diag, r=mejrs
Add `Sender` diagnostic item for `std::sync::mpsc::Sender`

Similar to the existing `Receiver` item, it will be used in Clippy to detect uses of `is_disconnected` that are racy.

Tracking issue: rust-lang/rust#153668
Suggested: https://github.com/rust-lang/libs-team/issues/748#issuecomment-4032790302
2026-04-24 02:42:51 -04:00
Jacob Pratt
0c253816ab Rollup merge of #155663 - nnethercote:eliminate-CrateMetadataRef, r=mejrs,petrochenkov
Eliminate `CrateMetadataRef`.

There are a number of things I dislike about `CrateMetadataRef`.
- It contains two fields `cstore` and `cdata`. The latter points to data within the former. It's like having an `Elem` type that has a reference to a vec element and also a reference to the vec itself. Weird.
- The `cdata` field gets a lot of use, and the `Deref` impl just derefs that field. The `cstore` field is rarely used.
- `CrateMetadataRef` is not a good name.
- Variables named `cdata` sometimes refer to values of this type and sometimes to values of type `CrateMetadata`, which is confusing.

The good news is that `CrateMetadataRef` is not necessary and can be replaced with `&CrateMetadata`. Why? Everywhere that `CrateMetadataRef` is used, a `TyCtxt` is also present, and the `CStore` is accessible from the `TyCtxt` with `CStore::from_tcx`.

So this commit removes `CrateMetadataRef` and replaces all its uses with `&CrateMetadata`. Notes:
- This requires adding only two uses of `CStore::from_tcx`, which shows how rarely the `cstore` field was used.
- `get_crate_data` now matches `get_crate_data_mut` more closely.
- A few variables are renamed for consistency, e.g. `data`/`cmeta` -> `cdata`.
- An unnecessary local variable (`local_cdata`) in `decode_expn_id` is removed.
- All the `CrateMetadataRef` methods become `CrateMetadata` methods, and their receiver changes from `self` to `&self`.
- `RawDefId::decode_from_cdata` is inlined and removed, because it has a single call site.

r? @mejrs
2026-04-24 02:42:51 -04:00
Jacob Pratt
cdba0cea17 Rollup merge of #155379 - ashivaram23:mir-query-cycle, r=saethlin
Avoid query cycles in DataflowConstProp

Fixes rust-lang/rust#155376 by skipping coroutines.
2026-04-24 02:42:50 -04:00
Jacob Pratt
b9cf909390 Rollup merge of #155081 - reddevilmidzy:ui-fixme, r=Kivooeo
Move and clean up some ui test

`ui/reserved` -> `ui/keyword`
`ui/deref-patterns` -> `ui/pattern/deref-patterns`
`ui/unknown-unstable-lints` -> `ui/lint/unknown-lints`

Tests related to unknown_lints that were located above lint have also been moved to a subdirectory, and duplicate tests have been deleted.

And delete unnecessary `//@ check-fail`

r? Kivooeo
2026-04-24 02:42:49 -04:00
Jacob Pratt
e002c6c726 Rollup merge of #155684 - bushrat011899:blanket_io_seek_for_ref, r=jhpratt
Generalize IO Traits for `Arc<T>` where `&T: IoTrait`

ACP: https://github.com/rust-lang/libs-team/issues/755
Tracking issue: https://github.com/rust-lang/rust/issues/154046
Related: rust-lang/rust#94744

## Description

After experimenting with rust-lang/rust#155625, I noticed `Seek` and `SeekFrom` can almost be moved to `core::io`. Unfortunately, the implementation of `Seek` for `Arc<File>` is a blocker for such a move, since `Arc` is not a fundamental type. This PR attempts to resolve this potential blocker by replacing the implementation with a more general alternative. An internal trait `IoHandle` has been added which types can implement to opt-in to `Read`/`Write`/`Seek` implementations for `Arc<Self>` as long as `&Self` implements said trait. Note that `BufRead` is excluded as the signature for `fill_buf` would require returning from a temporary.

Since this "blanket" implementation only applies to a single type which already implements the same traits, I believe this should have no user-facing impact.

If this PR was merged, rust-lang/rust#134190 could be replaced with a 2 line PR:
```rust
impl IoHandle for TcpStream {}
impl IoHandle for UnixStream {}
```
Likewise for any other types, a table of which can be found [here](https://github.com/rust-lang/libs-team/issues/504#issuecomment-2539569736). This is out of scope for this PR to avoid the need for an ACP.

---

## Notes

* See [this comment](https://github.com/rust-lang/rust/issues/154046#issuecomment-4303975612) for further details.
* No AI tooling of any kind was used during the creation of this PR.
2026-04-24 02:42:49 -04:00
Ralf Jung
ffc86e7eff Merge pull request #4978 from heitbaum/openssl-4.0.x
bump openssl-sys to support OpenSSL 4.0.x
2026-04-24 06:34:34 +00:00
Oli Scherer
986eabe707 Merge pull request #4979 from rust-lang/rustup-2026-04-24
Automatic Rustup
2026-04-24 06:17:00 +00:00
The Miri Cronjob Bot
a19421c61e Merge ref '9836b06b55f5' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@9836b06b55
Filtered ref: rust-lang/miri@94146760a7
Upstream diff: e22c616e4e...9836b06b55

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-24 05:51:28 +00:00
The Miri Cronjob Bot
e509d19dc3 Prepare for merging from rust-lang/rust
This updates the rust-version file to 9836b06b55.
2026-04-24 05:43:10 +00:00
Zac Harrold
7ba9478184 Implement Read/Write/Seek for Arc<T>
Added a marker trait `IoHandle` which can be used by the standard library to opt-in types to a blanket implementation of the various IO traits on `Arc<T>` where `&T: IoTrait` for some `IoTrait`.

The marker is required to avoid types like `Arc<[u8]>`  being included, since they don't have interior mutability and would not give expected results.
2026-04-24 14:26:09 +10:00
Ben Kimock
4b1f3926de Avoid query cycles in DataflowConstProp
* Avoid query cycles in DataflowConstProp
* Add -Zmir-opt-level=0 to the test
2026-04-24 03:04:03 +00:00
dianne
5276fcd28e prevent deref coercions in pin! 2026-04-23 19:55:51 -07:00
bors
d493b7c5ac Auto merge of #155710 - tgross35:rollup-skXlTFI, r=tgross35
Rollup of 7 pull requests

Successful merges:

 - rust-lang/rust#155660 (c-variadic: fix for sparc64)
 - rust-lang/rust#153482 (tests/ui/macros: add annotations for reference rules)
 - rust-lang/rust#155075 (Add docs about SDKs and C compilation on armv7a-vex-v5)
 - rust-lang/rust#155685 (Fix `get_child_at_index` return type hints)
 - rust-lang/rust#155686 (Fix array template arg lookup behavior)
 - rust-lang/rust#155689 (Const initialize `LOCK_LATCH` thread local)
 - rust-lang/rust#155690 (Fix classify_union to return Union for regular unions)
2026-04-24 02:27:01 +00:00
Rudi Heitbaum
c96d970f2d bump openssl-sys to support OpenSSL 4.0.x
The previously pinned version of openssl-sys is not compatible with
OpenSSL 4.0.x.

- `openssl-sys`: 0.9.111 -> 0.9.114
2026-04-24 01:33:16 +00:00
Zalathar
bcb1af095e Forbid *-pass and *-fail directives in tests/crashes
Crash tests are always expected to crash during compilation, so there is no
sensible meaning for specifying a pass/fail expectation in a crash test.
2026-04-24 11:10:57 +10:00
Trevor Gross
249332815f Rollup merge of #155690 - fneddy:fix_classify_union, r=jieyouxu
Fix classify_union to return Union for regular unions

Commit 623c7d7c4b accidentally changed the return value from REGULAR_UNION to RegularEnum when converting string literals to enum values. Commit b17670d3de then renamed RegularUnion to Union, but the buggy return statement remained unchanged. This caused unions to be misclassified as enums, preventing LLDB from displaying union field contents.
2026-04-23 20:32:52 -04:00
Trevor Gross
b7f0235416 Rollup merge of #155689 - zetanumbers:lock_latch_thread_local, r=ShoyuVanilla
Const initialize `LOCK_LATCH` thread local

A simple refactor to avoid runtime thread-local initialization.
2026-04-23 20:32:51 -04:00
Trevor Gross
b08772cd95 Rollup merge of #155686 - Walnut356:array_type, r=jieyouxu
Fix array template arg lookup behavior

Minor logic error. `get_template_args` expects a matching `<`/`>` pair. We were passing in an array type with the beginning `<` removed, so the template arg behavior would fail.
2026-04-23 20:32:51 -04:00
Trevor Gross
9ca29a862b Rollup merge of #155685 - Walnut356:ret_type, r=jieyouxu
Fix `get_child_at_index` return type hints

returning `None` is valid when the index is invalid, so the type hints should reflect that
2026-04-23 20:32:50 -04:00
Trevor Gross
8a12dc6c5e Rollup merge of #155075 - vexide:more-docs, r=ehuss
Add docs about SDKs and C compilation on armv7a-vex-v5

This PR expands the documentation for armv7a-vex-v5 to fix broken links, add more information about SDKs, and create a new section about C compilation.

I'm not super familiar with how Rust chooses what linker configuration to use / how the `cc` crate chooses what compiler to use - is this configuration to make C compilation work usually something that would be included in the compiler itself? Either way, it requires a lot of extra work which is kind of unfortunate (downloading a separate compiler, adding it to path, setting up a bunch of environment variables, and making a cargo config for linking).
2026-04-23 20:32:49 -04:00
Trevor Gross
6c683adbdf Rollup merge of #153482 - DanielEScherzer:test-references-macros, r=ehuss
tests/ui/macros: add annotations for reference rules
2026-04-23 20:32:48 -04:00
Trevor Gross
85468d1fdb Rollup merge of #155660 - folkertdev:sparc64-c-variadic, r=tgross35
c-variadic: fix for sparc64

tracking issue: https://github.com/rust-lang/rust/issues/44930

Turns out it's a big-endian target that right-adjusts values in the stack slots.

Apparently these tests do get run occasionally, though i don't think test failures are usually turned into issues on this repo. I guess we could add an assembly test here too, though really you just have to run these tests. I've tried this locally with qemu, and it passes all c-variadic tests.

cc @thejpster @glaubitz
r? tgross35
2026-04-23 20:32:48 -04:00
Trevor Gross
0a5785734c c-b: Ensure check-cfg is set for all targets
Emscripten and OpenBSD exit out of the build script early. Since
02014b06c1a3 ("c-b: Turn `mem-unaligned` from a feature to a cfg"), this
meant that the exit happened before all `rustc-check-cfg`s had been
emitted.

Rework the logic so these only skip the C build rather than the rest of
configuration.
2026-04-24 00:27:24 +00:00
Sidney Cammeresi
70fe8a6dc4 Add Sender diagnostic item for std::sync::mpsc::Sender
Similar to the existing `Receiver` item, it will be used in Clippy to
detect uses of `is_disconnected` that are racy.
2026-04-23 17:19:39 -07:00
Manish Goregaokar
b4e013bbec fix cstr clone_into unsoundness 2026-04-24 00:15:42 +00:00
Nicholas Nethercote
804e419ed8 Eliminate CrateMetadataRef.
There are a number of things I dislike about `CrateMetadataRef`.
- It contains two fields `cstore` and `cdata`. The latter points to data
  within the former. It's like having an `Elem` type that has a
  reference to a vec element and also a reference to the vec itself.
  Weird.
- The `cdata` field gets a lot of use, and the `Deref` impl just derefs
  that field. The `cstore` field is rarely used.
- `CrateMetadataRef` is not a good name.
- Variables named `cdata` sometimes refer to values of this type and
  sometimes to values of type `CrateMetadata`, which is confusing.

The good news is that `CrateMetadataRef` is not necessary and can be
replaced with `&CrateMetadata`. Why? Everywhere that `CrateMetadataRef`
is used, a `TyCtxt` is also present, and the `CStore` is accessible from
the `TyCtxt` with `CStore::from_tcx`.

So this commit removes `CrateMetadataRef` and replaces all its uses with
`&CrateMetadata`. Notes:
- This requires adding only two uses of `CStore::from_tcx`, which shows
  how rarely the `cstore` field was used.
- `get_crate_data` now matches `get_crate_data_mut` more closely.
- A few variables are renamed for consistency, e.g. `data`/`cmeta` ->
  `cdata`.
- An unnecessary local variable (`local_cdata`) in `decode_expn_id` is
  removed.
- All the `CrateMetadataRef` methods become `CrateMetadata` methods, and
  their receiver changes from `self` to `&self`.
- `RawDefId::decode_from_cdata` is inlined and removed, because it has a
  single call site.
2026-04-24 10:02:13 +10:00
dianne
e917fdccb4 add test 2026-04-23 17:00:30 -07:00
bors
9836b06b55 Auto merge of #155671 - nnethercote:simplify-Config-track_state, r=bjorn3
Simplify `Config::track_state`.

This is a callback used to track otherwise untracked state. It was added in rust-lang/rust#116731 for Clippy. (It was originally named `hash_untracked_state`, and examples in the rustc-dev-guide still use that name.) The `StableHasher` argument is unused, and probably has never been used. There is a FIXME comment pointing this out, which was added more than a year ago.

This commit removes the `StableHasher` callback argument. This also removes the need for `Options::untracked_state_hash`.

r? @bjorn3
2026-04-23 23:05:00 +00:00
dianqk
250beb3174 explicit-tail-calls: disable two tests on LoongArch for LLVM 22 also
Tail call support for LoongArch was reverted in LLVM 22 also.
2026-04-24 06:36:32 +08:00
Alex Crichton
874b7d3141 Remove myself as a maintainer of wasm32-wasip1-threads
Over time the landscape for myself has changed, and I no longer would
like to be officially listed as a maintainer of this target in Rust, so
I'm going to step down. There are still a number of others listed on
this target, however, so I'm sure they can address issues should they
come up.
2026-04-23 15:19:05 -07:00
Guillaume Gomez
7a07b79573 Remove AttributeLintKind::NonMetaItemDiagnosticAttribute variant 2026-04-23 23:08:40 +02:00
Guillaume Gomez
87b0ce595c Remove AttributeLintKind::MissingOptionsForDiagnosticAttribute variant 2026-04-23 23:00:38 +02:00
León Orell Valerian Liehr
07d015e566 Syntactically reject tuple index shorthands in struct patterns to fix a correctness regression 2026-04-23 22:28:00 +02:00
Ralf Jung
b366dcd27e Merge pull request #4971 from SpriteOvO/rv-weak-atomic-test
Use `AtomicUsize` instead of `AtomicBool` to test weak atomic for targets lacking byte-sized atomic
2026-04-23 18:46:03 +00:00
Asuna
d49039c8e2 Use AtomicUsize instead of AtomicBool to test weak atomic
Some architectures, such as RISC-V and LoongArch, lack support for
native byte-sized atomic operations, so weak operations fallback to
non-weak operations and are actually emulated by LL/SC loop, which never
fail.
2026-04-23 16:48:12 +00:00
bors
36ba2c7712 Auto merge of #155687 - GuillaumeGomez:rollup-aZ7YrAD, r=GuillaumeGomez
Rollup of 7 pull requests

Successful merges:

 - rust-lang/rust#155469 (Account for titlecase in casing lints)
 - rust-lang/rust#155644 (delegation: support self ty propagation for functions in free to trait reuse)
 - rust-lang/rust#154957 (Fix ICE when const closure appears inside a non-const trait method)
 - rust-lang/rust#155442 (Change keyword order for `impl` restrictions)
 - rust-lang/rust#155561 (Use singular wording for single _ placeholders in type suggestions)
 - rust-lang/rust#155637 (Fix E0191 suggestion for empty dyn trait args)
 - rust-lang/rust#155661 (Remove `AttributeLintKind` variants - part 6)
2026-04-23 15:55:48 +00:00
Vadim Petrochenkov
714df2bf00 privacy: Assert that compared visibilities are (usually) ordered
Also use `greater_than` instead of `is_at_least` for comparing visibilities, which we can do because visibilities are asserted to be ordered now.
2026-04-23 18:22:48 +03:00
Ralf Jung
e55e812a63 Merge pull request #4976 from bjorn3/windows_sys_0_61
Use windows-sys 0.61 in tests
2026-04-23 15:08:47 +00:00
Ralf Jung
2d5f931dd0 Merge pull request #4977 from WhySoBad/network-socket-disable-short-ops
Remove artificial short reads/writes from TCP sockets
2026-04-23 15:07:46 +00:00
Daria Sukhonina
892f176d89 Const initialize LOCK_LATCH thread local 2026-04-23 16:06:24 +03:00
Folkert de Vries
797059769e c-variadic: fix for sparc64
validated versus https://godbolt.org/z/qrM37rY6n
2026-04-23 14:46:44 +02:00
Guillaume Gomez
0a4e73e9bf Rollup merge of #155661 - GuillaumeGomez:rm-attributelintkind, r=JonathanBrouwer
Remove `AttributeLintKind` variants - part 6

Part of https://github.com/rust-lang/rust/issues/153099.

r? @JonathanBrouwer
2026-04-23 14:42:50 +02:00
Guillaume Gomez
8a4df7744f Rollup merge of #155637 - qaijuang:fix-e0191-empty-dyn-trait-suggestion, r=fmease
Fix E0191 suggestion for empty dyn trait args

Fixes rust-lang/rust#155578.
2026-04-23 14:42:49 +02:00
Guillaume Gomez
8c3864b6cc Rollup merge of #155561 - cijiugechu:fix/need-type-info-underscore-wording, r=adwinwhite
Use singular wording for single _ placeholders in type suggestions

While looking this part of code, I noticed this FIXME and fixed it :)
2026-04-23 14:42:48 +02:00
Guillaume Gomez
abce9f98d7 Rollup merge of #155442 - CoCo-Japan-pan:impl-restriction-reorder, r=Urgau,fmease,jhpratt
Change keyword order for `impl` restrictions

Based on rust-lang/rust#155222, this PR reorders keywords in trait definitions to group restrictions with visibility. It changes the order from `pub(...) const unsafe auto impl(...) trait Foo {...}`  to `pub(...) impl(...) const unsafe auto trait Foo {...}`.

Tracking issue for restrictions: rust-lang/rust#105077

r? @Urgau
cc @jhpratt
2026-04-23 14:42:47 +02:00
Guillaume Gomez
0595fcd195 Rollup merge of #154957 - lapla-cogito:issue_153891, r=oli-obk
Fix ICE when const closure appears inside a non-const trait method

Fixes rust-lang/rust#153891

`hir_body_const_context()` unconditionally delegated to the parent's const context for const closures, returning `None` when the parent had no const context. This caused `mir_const_qualif()` to hit a `span_bug!`, since `mir_promoted()` had already decided to call it based on the closure's own syntactic constness. Fall back to `ConstContext::ConstFn` when the parent's const context is `None`, so that the const closure body is still properly const-checked rather than triggering an ICE.

Examining [another attempt](https://github.com/rust-lang/rust/pull/153900/changes) at this issue (which has already been closed), I thought that its approach represents a workaround fix to avoid inconsistencies in the caller of `mir_promoted()`, whereas I think the correct behavior is for `hir_body_const_context()` itself to return the proper value.
2026-04-23 14:42:47 +02:00
Guillaume Gomez
aebbe6bb5f Rollup merge of #155644 - aerooneqq:delegation-self-ty-propagation-2, r=petrochenkov
delegation: support self ty propagation for functions in free to trait reuse

This PR adds support for self types specified in free to trait reuse. Up to this point we always generated `Self` despite the fact whether self type was specified or not. Now we use it in signature inheritance. Moreover we no more generate `Self` for static methods. Part of rust-lang/rust#118212.

```rust
trait Trait<T> {
  fn foo<const B: bool>(&self) {}
  fn bar() {}
}

impl<T> Trait<T> for usize {}

reuse <usize as Trait>::foo;

// Desugaring (no `Self` as usize is specified)
fn foo<T, const B: bool>(self: &usize) {
  <usize as Trait::<T>>::foo::<B>(self)
}

reuse Trait::bar;

// Desugaring (no `Self` as static method)
fn bar<T>() {
  Trait::<T>::bar(); //~ERROR: type annotations needed
}
```

r? @petrochenkov
2026-04-23 14:42:46 +02:00
Guillaume Gomez
4f4c1d553e Rollup merge of #155469 - Jules-Bertholet:titlecase-idents, r=petrochenkov
Account for titlecase in casing lints

Puts https://github.com/rust-lang/rust/issues/153892 to work.

Also contains fixes for Greek final sigma casing.

There are probably still some edge cases left to fix. Ideally we would use https://www.unicode.org/reports/tr55/#Identifier-Chunks as a base.

@rustbot label A-Unicode A-diagnostics A-lints A-suggestion-diagnostics
2026-04-23 14:42:45 +02:00
Guillaume Gomez
b716ebc7d1 Remove AttributeLintKind::IgnoredDiagnosticOption variant 2026-04-23 14:38:34 +02:00
Guillaume Gomez
f9cb684215 Remove AttributeLintKind::DiagnosticWrappedParserError variant 2026-04-23 14:38:34 +02:00
Guillaume Gomez
eb8be4f991 Remove AttributeLintKind::MalformedDiagnosticFormat variant 2026-04-23 14:38:34 +02:00
Guillaume Gomez
9bf2522cf0 Remove AttributeLintKind::MalFormedDiagnosticAttribute variant 2026-04-23 14:38:33 +02:00
Guillaume Gomez
ad11f2efec Remove AttributeLintKind::ExpectedNameValue variant 2026-04-23 14:33:25 +02:00
Guillaume Gomez
af3652c1dc Remove AttributeLintKind::ExpectedNoArgs variant 2026-04-23 14:33:25 +02:00
Guillaume Gomez
359910e21e Remove AttributeLintKind::MalformedDoc variant 2026-04-23 14:33:25 +02:00
Walnut
b86c9e77e0 fix array template arg lookup behavior 2026-04-23 07:32:33 -05:00
Qai Juang
4d2b607aa8 Fix E0191 suggestion for empty dyn trait args
* Fix E0191 suggestion for empty dyn trait args
* Fix tidy check
* address code nit
* fold test into existing E0191 test
2026-04-23 12:32:33 +00:00
bors
2eaa5de4a3 Auto merge of #155628 - nnethercote:CStore-from_tcx, r=mu001999
Streamline `CrateMetadataRef` construction in `provide_one!`.

`cstore.get_crate_data()` creates a `CrateMetadataRef`, which is exactly what we need. The current code is very confused and does several unnecessary things: mapping the `FreezeReadGuard` and calling `CStore::from_tcx` a second time to construct a second `CrateMetadataRef`.

This is a small perf win.

r? @mu001999
2026-04-23 12:32:22 +00:00
Walnut
c1936bad9b fix get_child_at_index return type hints 2026-04-23 07:27:44 -05:00
Ralf Jung
83a157f77b Merge pull request #4975 from RalfJung/internal_socket
unnamed_socket: do not introduce artifical short reads/writes
2026-04-23 12:26:26 +00:00
Eddy (Eduard) Stefes
2f99ab13f7 Fix classify_union to return Union for regular unions
Commit 623c7d7c4b accidentally changed the return value from
REGULAR_UNION to RegularEnum when converting string literals
to enum values. Commit b17670d3de then renamed RegularUnion
to Union, but the buggy return statement remained unchanged.
This caused unions to be misclassified as enums, preventing
LLDB from displaying union field contents.
2026-04-23 13:59:06 +02:00
mejrs
ce880a47fd Document #[diagnostic::on_move] in the unstable book 2026-04-23 13:40:45 +02:00
WhySoBad
c77b198e4b chore: disable short reads/writes for TCP sockets 2026-04-23 13:37:08 +02:00
Amanieu d'Antras
b15544d52f Handle index projections in call destinations in DSE
Since call destinations are evaluated after call arguments, we can't
turn copy arguments into moves if the same local is later used as an
index projection in the call destination.
2026-04-23 11:17:22 +01:00
bjorn3
bb80f4e4ba Use windows-sys 0.61 in tests
This version no longer requires using big import libraries and instead
uses raw-dylib.
2026-04-23 12:04:02 +02:00
bors
827651f220 Auto merge of #155674 - JonathanBrouwer:rollup-NG1fnzG, r=JonathanBrouwer
Rollup of 10 pull requests

Successful merges:

 - rust-lang/rust#146544 (mir-opt: Remove the workaround in UnreachableEnumBranching)
 - rust-lang/rust#154819 (Fix ICE for inherent associated type mismatches)
 - rust-lang/rust#155265 (Improved assumptions relating to isqrt)
 - rust-lang/rust#152576 (c-variadic: use `emit_ptr_va_arg` for  mips)
 - rust-lang/rust#154481 (Mark a function only used in nightly as nightly only)
 - rust-lang/rust#155614 (c-variadic: rename `VaList::arg` to `VaList::next_arg`)
 - rust-lang/rust#155630 (Make `//@ skip-filecheck` a normal compiletest directive)
 - rust-lang/rust#155641 (Remove non-working code for "running" mir-opt tests)
 - rust-lang/rust#155652 (Expand `Path::is_empty` docs)
 - rust-lang/rust#155656 (rustc_llvm: update opt-level handling for LLVM 23)
2026-04-23 08:38:23 +00:00
Jonathan Brouwer
0fa807c149 Rollup merge of #155656 - durin42:llvm-23-back-in-kansas, r=nikic
rustc_llvm: update opt-level handling for LLVM 23

LLVM 23 removed Os and Oz optimization pipelines and the PR says to use O2 with optsize or minsize instead as appropriate.

See https://github.com/llvm/llvm-project/pull/191363 for more details.
2026-04-23 09:38:26 +02:00
Jonathan Brouwer
f586047144 Rollup merge of #155652 - ChrisDenton:empty-docs, r=jhpratt
Expand `Path::is_empty` docs

Give some reasons why you might want to check if a path is empty. The `Path::join` behaviour can be surprising if you're not aware it might happen.
2026-04-23 09:38:26 +02:00
Jonathan Brouwer
333f033e20 Rollup merge of #155641 - Zalathar:no-run-mir-opt, r=jieyouxu
Remove non-working code for "running" mir-opt tests

Tests in `tests/mir-opt` always use `--emit=mir`, so the compiler doesn't even produce an executable.

Attempting to "run" these tests (e.g. with `./x test mir-opt --pass=run`) therefore fails when the OS notices that a MIR text file is not executable.

---

The second commit performs some semi-related cleanup.

r? jieyouxu
2026-04-23 09:38:25 +02:00
Jonathan Brouwer
610bfadb9b Rollup merge of #155630 - Zalathar:skip-filecheck, r=jieyouxu
Make `//@ skip-filecheck` a normal compiletest directive

The `skip-filecheck` directive is currently used by mir-opt tests, to suppress the default behaviour of running LLVM's `FileCheck` tool to check MIR output against FileCheck rules in the test file.

The `skip-filecheck` directive was not included in the big migration to `//@` directive syntax (https://github.com/rust-lang/rust/pull/121370), perhaps because it was parsed and processed in the *miropt-test-tools* helper crate, not in compiletest itself.

Recently I noticed that a small number of *codegen-llvm* tests were using the `//@ build-pass` directive, which has the non-obvious effect of skipping FileCheck in codegen tests. That's quite confusing, so I decided to have the mir-opt tests migrate over to a proper `//@ skip-filecheck` directive, which could then be used by codegen tests as well.

(I also added skip-filecheck support to assembly tests, which are very similar to codegen tests, though there are currently no assembly tests that actually use `//@ skip-filecheck`.)

---

Support for using `//@ build-pass` in codegen tests to skip FileCheck was introduced in https://github.com/rust-lang/rust/pull/113603. With hindsight, I think doing things that way was pretty clearly a  mistake, and we'll be better off with `//@ skip-filecheck`.

r? jieyouxu
2026-04-23 09:38:24 +02:00
Jonathan Brouwer
d289cc7f53 Rollup merge of #155614 - folkertdev:rename-next-arg, r=tgross35
c-variadic: rename `VaList::arg` to `VaList::next_arg`

tracking issue: https://github.com/rust-lang/rust/issues/44930

per [the T-libs-api meeting](https://hackmd.io/d9D6vUnuTnCWygkc3hffEw#nominated-rusttf44930-Tracking-issue-for-RFC-2137-Support-defining-C-compatible-variadic-functions-in-Rust-c_variadic), rename `VaList::arg` to `VaList::next_arg`.
2026-04-23 09:38:23 +02:00
Jonathan Brouwer
421a94fc88 Rollup merge of #154481 - ferrocene:hoverbear/flag-off-unused-code, r=wesleywiser
Mark a function only used in nightly as nightly only

If you run `./x.py test rustc_next_trait_solver` you'll currently see a failure:

```
warning: method `merge` is never used
  --> compiler/rustc_abi/src/callconv.rs:38:8
   |
25 | impl HomogeneousAggregate {
   | ------------------------- method in this implementation
...
38 |     fn merge(self, other: HomogeneousAggregate) -> Result<HomogeneousAggregate, Heterogeneous> {
   |        ^^^^^
   |
   = note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default

warning: `rustc_abi` (lib) generated 1 warning
```

This is because the usages are behind a nightly feature flag:

fda6d37bb8/compiler/rustc_abi/src/callconv.rs (L52)

fda6d37bb8/compiler/rustc_abi/src/callconv.rs (L131)

fda6d37bb8/compiler/rustc_abi/src/callconv.rs (L167)

This does the flag off.

Test on `main` and this branch:

```
./x.py test rustc_next_trait_solver
```
2026-04-23 09:38:23 +02:00
Jonathan Brouwer
6cc506c5db Rollup merge of #152576 - folkertdev:mips-va-arg, r=tgross35
c-variadic: use `emit_ptr_va_arg` for  mips

tracking issue: https://github.com/rust-lang/rust/issues/44930

After reading the implementation carefully, I believe it really is just `emit_ptr_va_arg`.

The LLVM implementation can be found here: 289a3292be/llvm/lib/Target/Mips/MipsISelLowering.cpp (L2338).

r? workingjubilee
2026-04-23 09:38:22 +02:00
Jonathan Brouwer
04bcb393ab Rollup merge of #155265 - Apersoma:isqrt-smarter, r=jhpratt,tgross35
Improved assumptions relating to isqrt

Improved various assumptions relating to values yielded by `isqrt`.
Does not solve but does improve rust-lang/rust#132763.

Re-openeing of rust-lang/rust#154115

Added assumptions are:
* if `x` is nonzero then `x.isqrt()`  is nonzero
* `x.isqrt() <= x`
* `x.isqrt() * x.isqrt() <= x`
2026-04-23 09:38:21 +02:00
Jonathan Brouwer
280345333a Rollup merge of #154819 - cijiugechu:fix-next-solver-inherent-iat-ice, r=jackh726
Fix ICE for inherent associated type mismatches

Avoid projection-only suggestions for inherent associated types.

Closes rust-lang/rust#154333
Closes rust-lang/rust#155204
2026-04-23 09:38:20 +02:00
Jonathan Brouwer
032b666d6a Rollup merge of #146544 - dianqk:rm-workaround, r=wesleywiser
mir-opt: Remove the workaround in UnreachableEnumBranching

rust-lang/rust#120268 added a workaround due to the compile time of TailDuplicator.

LLVM 20 has resolved this in llvm/llvm-project#114990 and llvm/llvm-project#132536.
2026-04-23 09:38:20 +02:00
teor
34c0fe8778 Fix some typos 2026-04-23 17:07:21 +10:00
teor
140dad0080 Resolve FIXME: os = none is bare metal 2026-04-23 17:07:21 +10:00
teor
c0441d42ed Fix Mlibc env pretty print to Managarm C Library 2026-04-23 17:07:21 +10:00
aerooneqq
78435a9ff8 Remove #![allow(incomplete_features)] from delegation tests 2026-04-23 09:37:48 +03:00
bors
92c7010294 Auto merge of #155609 - cuviper:thread_pool-seq-cst, r=jieyouxu
rustc_thread_pool: Make `CoreLatch::set` use `SeqCst` instead of `AcqRel`

Every other modification of this variable uses `SeqCst`, which is justified in the sleep README. This particular choice of `AcqRel` was not discussed during its addition in rayon-rs/rayon#746, nor rayon-rs/rfcs#5, so I suspect was simply an oversight from earlier development. We probably do want this to participate in the same sequential consistency.

The only other ordering difference is `CoreLatch::probe`'s load with `Acquire`, which should be fine because this doesn't need consistency with the sleep counters.

See also rayon-rs/rayon#1297. As I commented there, I think in practice this would be quite rare to cause any problems, but it *could* be a source of non-deterministic bugs on targets with weak memory ordering.
2026-04-23 05:30:11 +00:00
Nicholas Nethercote
3c5e7e8969 Simplify Config::track_state.
This is a callback used to track otherwise untracked state. It was added
in #116731 for Clippy. (It was originally named `hash_untracked_state`,
and examples in the rustc-dev-guide still use that name.) The
`StableHasher` argument is unused, and probably has never been used.
There is a FIXME comment pointing this out, which was added more than a
year ago.

This commit removes the `StableHasher` callback argument. This also
removes the need for `Options::untracked_state_hash`.
2026-04-23 15:02:55 +10:00
Jules Bertholet
0dca30756d Account for titlecase in casing lints 2026-04-23 00:43:18 -04:00
Lewis McClelland
4f7a26f10d Update maintainers of armv7a-vex-v5 2026-04-22 23:03:22 -04:00
bors
5095b44caf Auto merge of #154596 - alexcrichton:update-wasi-sdk, r=jieyouxu
Update to wasi-sdk-32 in CI/releases

Similar to prior updates such as rust-lang/rust#149037. This notably pulls in some bug fixes for wasi-libc around nonblocking I/O and networking.
2026-04-23 01:39:51 +00:00
Folkert de Vries
e9ab558406 va_arg: use emit_ptr_va_arg for mips 2026-04-23 01:20:59 +02:00
Folkert de Vries
328d05309c c-variadic: add mips assembly test 2026-04-23 01:09:37 +02:00
Folkert de Vries
ca43552c13 add the mem feature back to compiler-builtins/Cargo.toml
this was removed by accident before, and only discovered now that we're syncing with the main repo
2026-04-23 00:59:32 +02:00
bors
30837cb66d Auto merge of #155550 - zetanumbers:cache_insert_unique, r=oli-obk
Replace `ShardedHashMap` method `insert` with debug-checked `insert_unique`

Currently every use of `ShardedHashMap::insert` checks that it won't evict an old value due to unique key. I haven't found any issue related to that faulty condition, so I thought of replacing it with `ShardedHashMap::insert_unique` which doesn't check for this condition unless `debug_assertions` are enabled. This might improve the performance.

r? @petrochenkov
2026-04-22 22:28:22 +00:00
Apersoma
e722ba58ed improved assumptions relating isqrt (squashed) 2026-04-22 21:58:59 +00:00
Yotam Ofek
ab1500b8ab Separate out some IndexItem fields into a new struct and DRY 2026-04-22 23:49:24 +03:00
cyrgani
11ba127dfc move remaining files from deriving to derives 2026-04-22 20:26:08 +00:00
cyrgani
e908aa8671 delete some no-longer-meaningful tests 2026-04-22 20:22:40 +00:00
cyrgani
b0b5b1256a create derives/clone-copy 2026-04-22 20:22:40 +00:00
cyrgani
818e51128e create derives/eq-ord 2026-04-22 20:22:40 +00:00
cyrgani
87a26ec40b create derives/default 2026-04-22 20:22:40 +00:00
cyrgani
674eb8a04d create derives/debug 2026-04-22 20:22:40 +00:00
cyrgani
f2657b8991 create derives/coercepointee 2026-04-22 20:22:40 +00:00
bors
913e4bea83 Auto merge of #155655 - JonathanBrouwer:rollup-KFUw3UR, r=JonathanBrouwer
Rollup of 10 pull requests

Successful merges:

 - rust-lang/rust#154794 (Add on_unmatch_args)
 - rust-lang/rust#155133 (Document precision considerations of `Duration`-float methods)
 - rust-lang/rust#154283 (Remove `nodes_in_current_session` field and related assertions)
 - rust-lang/rust#155374 (rustdoc: fix a few spots where emit isn't respected)
 - rust-lang/rust#155587 (Immediately feed visibility on DefId creation)
 - rust-lang/rust#155622 (c-variadic: `va_arg` fixes )
 - rust-lang/rust#155629 (rustc_public: Add `constness` & `asyncness` in `FnDef`)
 - rust-lang/rust#155632 (Some metadata cleanups)
 - rust-lang/rust#155639 (BinOpAssign always returns unit)
 - rust-lang/rust#155647 (rustc-dev-guide subtree update)
2026-04-22 19:16:27 +00:00
Brian Smith
3a0a14fd7c <Take as Read>::read_buf: Don't initialize buf if it was already initialized. 2026-04-22 11:38:04 -07:00
Brian Smith
c716ce5c2e <Take as Read>::read_buf: Clarify safety comments and naming. 2026-04-22 11:38:04 -07:00
Brian Smith
71076f2338 <Take as Read>::read_buf: Eliminate unneeded local variables.
Eliminate `cursor` and `ibuf` as named variables, as their presence
makes things more confusing.
2026-04-22 11:36:50 -07:00
Brian Smith
4abc28f570 <Take as Read>::read_buf: Clarify local variable name. 2026-04-22 11:34:05 -07:00
Chris Denton
110e67c9c2 Expand Path::is_empty docs 2026-04-22 17:41:52 +00:00
Augie Fackler
f6b8f0b6f1 rustc_llvm: update opt-level handling for LLVM 23
LLVM 23 removed Os and Oz optimization pipelines and the PR says to use
O2 with optsize or minsize instead as appropriate.
2026-04-22 13:25:35 -04:00
Jonathan Brouwer
e94e3ccca8 Rollup merge of #155647 - tshepang:rdg-sync, r=tshepang
rustc-dev-guide subtree update

Subtree update of `rustc-dev-guide` to bed088a2db.

Created using https://github.com/rust-lang/josh-sync.

r? @ghost
2026-04-22 19:18:33 +02:00
Jonathan Brouwer
c4b5ea9625 Rollup merge of #155639 - oli-obk:builtin-binop-const, r=nnethercote
BinOpAssign always returns unit

I don't know why we treated assign ops as returning their binop type sometimes, but it's usually ignored later anyway and mostly affects infer vars.

Also updated a comment from 11 years ago when SIMD types apparently had builtin `==` logic.
2026-04-22 19:18:32 +02:00
Jonathan Brouwer
6f6e6bb485 Rollup merge of #155632 - nnethercote:split-Metadata, r=mejrs
Some metadata cleanups

Details in individual commits.

r? @mejrs
2026-04-22 19:18:32 +02:00
Jonathan Brouwer
b0d794f425 Rollup merge of #155629 - cijiugechu:fn_constness, r=makai410
rustc_public: Add `constness` & `asyncness` in `FnDef`

Resolves [https://github.com/rust-lang/project-stable-mir/issues/111](https://github.com/rust-lang/project-stable-mir/issues/111).
2026-04-22 19:18:31 +02:00
Jonathan Brouwer
e9972d9dec Rollup merge of #155622 - folkertdev:va-arg-llvm-fixes, r=tgross35
c-variadic: `va_arg` fixes

tracking issue: https://github.com/rust-lang/rust/issues/44930

extracts some generic LLVM `va_arg` fixes from https://github.com/rust-lang/rust/pull/152576 and https://github.com/rust-lang/rust/pull/155429.

r? tgross35
2026-04-22 19:18:30 +02:00
Jonathan Brouwer
5e48418496 Rollup merge of #155587 - oli-obk:feed-visibility-no-hash, r=petrochenkov
Immediately feed visibility on DefId creation

This system was originally introduced in rust-lang/rust#121089

This PR was enabled by refactorings in rust-lang/rust#154945, because after that, the visibility feeding happens directly after the `DefId` creation, so we don't need to go through the intermediate hash table anymore

Should unblock rust-lang/rust#138995
2026-04-22 19:18:29 +02:00
Jonathan Brouwer
dcde112616 Rollup merge of #155374 - notriddle:non-static-dep-info, r=fmease
rustdoc: fix a few spots where emit isn't respected

Addresses the third list item of rust-lang/rust#155298
2026-04-22 19:18:29 +02:00
Jonathan Brouwer
8bade0362d Rollup merge of #154283 - Zoxc:rem-nodes_in_current_session, r=nnethercote
Remove `nodes_in_current_session` field and related assertions

This removes the `nodes_in_current_session` field and related assertions. These are enabled if `-Z incremental-verify-ich` is passed or `debug_assertions` is on. Historically these have been useful to catch query keys with improper `HashStable` impls which lead to collisions.

We currently also check for duplicate nodes when loading the dep graph. This check is more complete as it covers the entire dep graph and is enabled by default. It doesn't provide a query key for a collision however. This check is also delayed to the next incremental session.

We also have the `verify_query_key_hashes` which is also enabled if `-Z incremental-verify-ich` is passed or `debug_assertions` is on. This checks for dep node conflicts in each query cache and provides 2 conflicting keys if present.

I think these remaining checks are sufficient and so we can remove `nodes_in_current_session`.
2026-04-22 19:18:28 +02:00
Jonathan Brouwer
d7bb378724 Rollup merge of #155133 - cuviper:duration_fp_docs, r=the8472
Document precision considerations of `Duration`-float methods

A `Duration` is essentially a 94-bit value (64-bit sec and ~30-bit ns),
so there's some inherent loss when converting to floating-point for
`mul_f64` and `div_f64`. We could go to greater lengths to compute these
with more accuracy, like rust-lang/rust#150933 or rust-lang/rust#154107,
but it's not clear that it's worth the effort. The least we can do is
document that some rounding is to be expected, which this commit does
with simple examples that only multiply or divide by `1.0`.

This also changes the `f32` methods to just forward to `f64`, so we keep
more of that duration precision, as the range is otherwise much more
limited there.
2026-04-22 19:18:27 +02:00
Jonathan Brouwer
5ad7363c39 Rollup merge of #154794 - chenyukang:yukang-fix-152494-incomplete-macro-args, r=mejrs
Add on_unmatch_args

Fixes rust-lang/rust#152494
r? @estebank
2026-04-22 19:18:26 +02:00
Ralf Jung
17aae34a1f rename unnamed_socket -> virtual_socket 2026-04-22 17:52:30 +02:00
bors
f676c20edd Auto merge of #155343 - dianqk:indirect-by-ref, r=nikic
codegen: Copy to an alloca when the argument is neither by-val nor by-move for indirect pointer.



Fixes https://github.com/rust-lang/rust/issues/155241.

When a value is passed via an indirect pointer, the value needs to be copied to a new alloca. For x86_64-unknown-linux-gnu, `Thing` is the case:

```rust
#[derive(Clone, Copy)]
struct Thing(usize, usize, usize);

pub fn foo() {
    let thing = Thing(0, 0, 0);
    bar(thing);
    assert_eq!(thing.0, 0);
}

#[inline(never)]
#[unsafe(no_mangle)]
pub fn bar(mut thing: Thing) {
    thing.0 = 1;
}
```

Before passing the thing to the bar function, the thing needs to be copied to an alloca that is passed to bar.

```llvm
%0 = alloca [24 x i8], align 8
call void @llvm.memcpy.p0.p0.i64(ptr align 8 %0, ptr align 8 %thing, i64 24, i1 false)
call void @bar(ptr %0)
```

This patch applies the rule to the untupled arguments as well.

```rust
#![feature(fn_traits)]

#[derive(Clone, Copy)]
struct Thing(usize, usize, usize);

#[inline(never)]
#[unsafe(no_mangle)]
pub fn foo() {
    let thing = (Thing(0, 0, 0),);
    (|mut thing: Thing| {
        thing.0 = 1;
    }).call(thing);
    assert_eq!(thing.0.0, 0);
}
```

For this case, this patch changes from

```llvm
; call example::foo::{closure#0}
call void @_RNCNvCs15qdZVLwHPA_7example3foo0B3_(ptr ..., ptr %thing)
```

to

```llvm
%0 = alloca [24 x i8], align 8
call void @llvm.memcpy.p0.p0.i64(ptr align 8 %0, ptr align 8 %thing, i64 24, i1 false)
; call example::foo::{closure#0}
call void @_RNCNvCs15qdZVLwHPA_7example3foo0B3_(ptr ..., ptr %0)
```

However, the same rule cannot be applied to tail calls that would be unsound, because the caller's stack frame is overwritten by the callee's stack frame. Fortunately, https://github.com/rust-lang/rust/pull/151143 has already handled the special case. We must not copy again.

No copy is needed for by-move arguments, because the argument is passed to the called "in-place".

No copy is also needed for by-val arguments, because the attribute implies that a hidden copy of the pointee is made between the caller and the callee.


NOTE: The patch has a trick for tail calls that we pass by-move. We can choose to copy an alloca even for by-move arguments, but tail calls require MUST-by-move.
2026-04-22 15:47:21 +00:00
Ralf Jung
2f73eeea8b unnamed_socket: do not introduce artifical short reads/writes 2026-04-22 17:46:49 +02:00
Folkert de Vries
84cd23b3c8 c-variadic: rename VaList::arg to VaList::next_arg 2026-04-22 16:02:11 +02:00
Tshepang Mbambo
85ffe928d8 Merge pull request #2846 from rust-lang/tshepang/sembr
sembr some files
2026-04-22 15:14:09 +02:00
Tshepang Mbambo
a39bff7112 reflow 2026-04-22 15:07:45 +02:00
Tshepang Mbambo
f7f7989c06 sembr src/name-resolution.md 2026-04-22 14:50:02 +02:00
Tshepang Mbambo
ca75ba2345 improve coherence.md 2026-04-22 14:49:12 +02:00
Tshepang Mbambo
78b3073a74 sembr src/coherence.md 2026-04-22 14:47:52 +02:00
dianqk
a21eee0396 Update LLVM to 22.1.4 2026-04-22 20:30:52 +08:00
aerooneqq
abd8c38a28 Support self ty propagation for functions in free to trait reuse 2026-04-22 15:24:30 +03:00
Tshepang Mbambo
dc675c72d3 improve hir/lowering.md 2026-04-22 14:23:38 +02:00
Tshepang Mbambo
14dd4b2086 sembr src/hir/lowering.md 2026-04-22 14:18:09 +02:00
Tshepang Mbambo
e704d0f624 improve stability.md 2026-04-22 14:08:22 +02:00
cyrgani
72c56ed0c0 remove deriving-via-extension-*.rs tests 2026-04-22 11:35:02 +00:00
yukang
8d75f0cbfc add on_unmatch_args 2026-04-22 19:28:44 +08:00
Zalathar
1a3c6b481c Don't pass local_pm to compile_test_general
This argument is only used to inhibit `#![allow(unused)]` for `//@ run-pass` UI
tests.

No callers actually need to override this value, even when doing unusual
things, so we can just look it up inside the method body instead.
2026-04-22 21:15:32 +10:00
Zalathar
8172f47781 Remove non-working code for "running" mir-opt tests
Tests in `tests/mir-opt` always use `--emit=mir`, so the compiler doesn't even
produce an executable.

Attempting to "run" these tests (e.g. with `./x test mir-opt --pass=run`)
therefore fails when the OS notices that a MIR text file is not executable.
2026-04-22 21:15:32 +10:00
Tshepang Mbambo
c392defd21 sembr src/stability.md 2026-04-22 12:48:54 +02:00
Oli Scherer
3be0e76c36 Update a very outdated comment 2026-04-22 12:37:08 +02:00
Tshepang Mbambo
a3a299256a sembr src/tests/compiletest.md 2026-04-22 12:36:35 +02:00
Tshepang Mbambo
6ff11cfdde make sentence feel more complete 2026-04-22 12:35:20 +02:00
Tshepang Mbambo
0be2aa6e27 sembr src/tests/ci.md 2026-04-22 12:33:55 +02:00
Tshepang Mbambo
4d31601bef title case 2026-04-22 12:31:32 +02:00
Tshepang Mbambo
5f0877e21b whitespace 2026-04-22 12:28:46 +02:00
Tshepang Mbambo
248cfe7312 sembr src/rustc-driver/external-rustc-drivers.md 2026-04-22 12:27:16 +02:00
Oli Scherer
24b1634898 BinOpAssign always returns unit 2026-04-22 12:27:03 +02:00
Tshepang Mbambo
abb0d9a3f1 Merge pull request #2845 from rust-lang/rustc-pull
Rustc pull update
2026-04-22 12:11:27 +02:00
The rustc-josh-sync Cronjob Bot
95f4108b3a Merge ref 'cf1817bc6ecd' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@cf1817bc6e
Filtered ref: rust-lang/rustc-dev-guide@df639463eb
Upstream diff: 84c1190072...cf1817bc6e

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-22 10:00:56 +00:00
The rustc-josh-sync Cronjob Bot
3bb7d7d8a4 Prepare for merging from rust-lang/rust
This updates the rust-version file to cf1817bc6e.
2026-04-22 10:00:53 +00:00
Zalathar
1e8cd1f7a6 Support //@ skip-filecheck in codegen and assembly tests
Skipping FileCheck in codegen/assembly tests is normally not very useful, but a
small number of existing tests were using `//@ build-pass` to do so anyway, so
it's clearer for them to explicitly use `//@ skip-filecheck` instead.
2026-04-22 19:55:27 +10:00
Zalathar
eb6eed4ba7 Make //@ skip-filecheck a normal compiletest directive 2026-04-22 19:55:11 +10:00
Daria Sukhonina
fa4d2ad671 Clarify behavior of ShardedHashMap::insert_unique 2026-04-22 12:39:19 +03:00
dianqk
10d8329061 codegen: Copy to an alloca when the argument is neither by-val nor by-move for indirect pointer. 2026-04-22 17:37:17 +08:00
dianqk
e67e7162f7 Add miscompiled test cases 2026-04-22 17:36:33 +08:00
Folkert de Vries
5149a31515 change llvm.ptrmask argument to isize
we were saying that the type is i32, but would often provide an i64.
That never failed so far, but starts failing (like, crashing LLVM) when
working with 128-bit values that are 16-byte aligned. So, we may as well
use the more robust approach now.
2026-04-22 10:32:27 +02:00
Tshepang Mbambo
f9566d6b10 Merge pull request #2844 from rust-lang/aj/rustc-internals-docs-clarity
Mentions rustc-docs for rustc_private
2026-04-22 09:50:10 +02:00
lapla
9be8fca54e Fix ICE when const closure appears inside a non-const trait method 2026-04-22 15:41:31 +09:00
bors
cf1817bc6e Auto merge of #155634 - jhpratt:rollup-lo99oO5, r=jhpratt
Rollup of 7 pull requests

Successful merges:

 - rust-lang/rust#155589 (Forbid `check-pass`/`build-pass`/`run-pass` directives in incremental tests)
 - rust-lang/rust#155610 (Add missing `dyn` keyword to `trait_alias` page of the Unstable Book)
 - rust-lang/rust#155615 (test cleanups for `ui/derives` and `ui/deriving`)
 - rust-lang/rust#154874 (Fix ICE for inherited const conditions on const closures)
 - rust-lang/rust#155605 (std: Update support for `wasm32-wasip3`)
 - rust-lang/rust#155613 (c-variadic: tweak `std` docs)
 - rust-lang/rust#155619 (Remove a bunch of unnecessary explicit lifetimes from the ast validator)
2026-04-22 06:20:12 +00:00
Jacob Pratt
6fa2b1d01a Rollup merge of #155619 - oli-obk:ast-validation-lifetimes, r=dingxiangfei2009
Remove a bunch of unnecessary explicit lifetimes from the ast validator

Noticed while fiddling with error reporting. None of the lifetimes were ever used for anything
2026-04-22 01:53:43 -04:00
Jacob Pratt
48f36eda77 Rollup merge of #155613 - folkertdev:c-variadic-doc-tweaks, r=tgross35
c-variadic: tweak `std` docs

tracking issue: https://github.com/rust-lang/rust/issues/44930

In preparation of a rename of `arg` to `next_arg`

cc @workingjubilee
r? tgross35
2026-04-22 01:53:42 -04:00
Jacob Pratt
6c0cbcf038 Rollup merge of #155605 - alexcrichton:wasip3, r=jhpratt
std: Update support for `wasm32-wasip3`

This commit performs some minor update within the standard library for the `wasm32-wasip3` target. This target is a tier 3 target currently due to the WASIp3 specification not being officially released. This commit adds a dependency from the standard library on the `wasip3` crate in the same manner as the `wasip1` and `wasip2` crates that it already depends on. The use-sites, for randomness and environment variables, are then updated to handle the wasip2/wasip3 multiplexing.
2026-04-22 01:53:42 -04:00
Jacob Pratt
b622dd00fb Rollup merge of #154874 - cijiugechu:fix-const-closure-inherited-conditions, r=oli-obk
Fix ICE for inherited const conditions on const closures

Synchronize `evaluate_host_effect_for_fn_goal` with the behavior of `extract_fn_def_from_const_callable` in new solver.

Closes rust-lang/rust#153861 .
2026-04-22 01:53:41 -04:00
Jacob Pratt
ca4aaafbf2 Rollup merge of #155615 - cyrgani:clean-deriving, r=Kivooeo
test cleanups for `ui/derives` and `ui/deriving`

The eventual goal is for `ui/deriving` to be merged into `ui/derives` entirely. This PR focuses on the `issue-*.rs` tests in `deriving` and a few other no-longer-useful tests.
r? @Kivooeo
2026-04-22 01:53:40 -04:00
Jacob Pratt
0ab2cdf261 Rollup merge of #155610 - Omnikar:trait-alias-docs-fix, r=mejrs
Add missing `dyn` keyword to `trait_alias` page of the Unstable Book

There seemed to be a small typo in the Rust Unstable Book page for the `trait_alias` feature, where a variable is declared as `&Bar` for a trait `Bar`, rather than `&dyn Bar`.
2026-04-22 01:53:39 -04:00
Jacob Pratt
2a68b22174 Rollup merge of #155589 - Zalathar:cpass, r=jieyouxu
Forbid `check-pass`/`build-pass`/`run-pass` directives in incremental tests

- Follow-up to https://github.com/rust-lang/rust/pull/155474
---

This PR forbids the use of `//@ check-pass`, `//@ build-pass`, and `//@ run-pass` directives in incremental tests. Tests that would have used those directives should use a revision name beginning with `cpass`/`bpass`/`rpass` instead.

(The `*-fail` directives are already forbidden in incremental tests.)

Existing incremental tests that used the `check-pass` and `build-pass` directives have been migrated. To allow migration of the check-pass tests, this PR also adds support for revision names beginning with `cpass`. No incremental tests were using `run-pass`.

---

Several of the migrated `build-pass` tests have a FIXME indicating that they could potentially be migrated to `check-pass` instead. This PR does not perform that migration.

In the future, I intend to do more cleanup of how compiletest handles pass/fail expectations, but I didn't want to cram too much into one PR.

r? jieyouxu
2026-04-22 01:53:39 -04:00
Nicholas Nethercote
f0ebd66eaa Remove unused tcx params.
They are unused because of the previous commit.
2026-04-22 13:54:57 +10:00
Nicholas Nethercote
be52e75d69 Simplify one MetaBlob impl.
It's currently an impl for `(CrateMetadataRef, TyCtxt)`, but (a) the
`TyCtxt` is not used, and (b) the `CrateMetadataRef` can be simplified
to a `CrateMetadata` because `CStore` access isn't required. This
require changing `blob` to take `&self`, which is no big deal, and it
simplifies many `get` calls.
2026-04-22 13:25:15 +10:00
Nicholas Nethercote
2f864a9d03 Split Metadata trait into MetaBlob and MetaDecoder.
`Metadata` has two methods, `blob` and `decoder`, which are not used
together. Splitting the trait in two will allow some cleanups in
subsequent commits.
2026-04-22 13:13:25 +10:00
bors
1bfcb284f7 Auto merge of #155392 - WaffleLapkin:alias-termmm, r=BoxyUwU
`AliasTerm` refactor

follow up to https://github.com/rust-lang/rust/pull/154758
tracking issue: https://github.com/rust-lang/rust/issues/154941
2026-04-22 02:57:46 +00:00
Zalathar
87ec57f3a1 Forbid *-pass directives in incremental tests
Incremental tests that would have used the `check-pass`, `build-pass`, or
`run-pass` directives should instead use a revision name starting with
`cpass`/`bpass`/`rpass` as appropriate.
2026-04-22 12:34:14 +10:00
Zalathar
edbb86264d Add support for cpass incremental revisions 2026-04-22 12:34:14 +10:00
Zalathar
0ea8958c02 Migrate bfail/build-pass tests to bpass (2/2)
This is the subset of incremental tests that have a FIXME to consider migrating
to check-pass instead.

That migration is beyond the scope of this PR, but might be attempted later.
2026-04-22 12:28:25 +10:00
Zalathar
793c646b7b Migrate bfail/build-pass tests to bpass (1/2)
This is the subset of incremental tests that should continue to use `bpass`
even after `cpass` is supported, because they (presumably) involve codegen.
2026-04-22 12:28:25 +10:00
cijiugechu
b90687377c Add constness & asyncness 2026-04-22 10:22:14 +08:00
Nicholas Nethercote
cb3df68743 Streamline CrateMetadataRef construction in provide_one!.
`cstore.get_crate_data()` creates a `CrateMetadataRef`, which is exactly
what we need. The current code is very confused and does several
unnecessary things: mapping the `FreezeReadGuard` and calling
`CStore::from_tcx` a second time to construct a second
`CrateMetadataRef`.

This is a small perf win.
2026-04-22 12:21:04 +10:00
bors
f9988fefd3 Auto merge of #155611 - JonathanBrouwer:rollup-hUV99y1, r=JonathanBrouwer
Rollup of 5 pull requests

Successful merges:

 - rust-lang/rust#155546 (Improve E0308 error message for `impl Trait` return mismatches)
 - rust-lang/rust#152834 (Fix incorrect `let` to `const` suggestion for pattern bindings)
 - rust-lang/rust#155425 (Remove duplicated `Flags` methods.)
 - rust-lang/rust#155547 (Use per-parent disambiguators everywhere)
 - rust-lang/rust#155590 (Remove AttributeLintKind variants - part 5)
2026-04-21 23:34:47 +00:00
Daniel Scherzer
05485026ad tests/ui/macros: add annotations for reference rules 2026-04-21 15:46:04 -07:00
Folkert de Vries
45f98b9aa7 va_arg: remove unused argument 2026-04-22 00:07:01 +02:00
Folkert de Vries
0169aaea31 va_arg: fix potential misaligned load 2026-04-22 00:06:54 +02:00
mejrs
70cf3f4fda Put #[diagnostic::on_move] on File 2026-04-21 23:42:33 +02:00
Oli Scherer
fe2e5a9cfa Remove a bunch of unnecessary explicit lifetimes from the ast validator 2026-04-21 23:21:23 +02:00
Oli Scherer
3070ce9d1b Immediately feed visibility on DefId creation 2026-04-21 22:45:34 +02:00
Oli Scherer
af03b49b25 Handle MacCall items directly in the def collector
instead of entangling it with the brg logic
2026-04-21 22:45:03 +02:00
Oli Scherer
209a2a6e33 delegation macros are never handled in the def collector 2026-04-21 22:45:03 +02:00
Oli Scherer
797e68f240 Move variant ctor creation into the brg 2026-04-21 22:45:03 +02:00
Oli Scherer
af3e34bf65 Stop creating ctor def ids for unions and move the ctor def id creation into the brg 2026-04-21 22:45:03 +02:00
Folkert de Vries
6ca836bc5b c-variadic: tweak std docs 2026-04-21 22:44:26 +02:00
bors
9ec5d5f32e Auto merge of #155604 - weihanglo:update-cargo, r=weihanglo
Update cargo submodule

9 commits in 7ecf0285ebb408d596e4a8ac76a0980d8edb7005..06ac0e7c05770a8c7bbf67bdd12fa1a1eefdc8ae
2026-04-18 15:34:11 +0000 to 2026-04-21 15:33:56 +0000
- test(git): add regression test for full-hash GitHub fast path (rust-lang/cargo#16919)
- fix(help): add `.1` extension to man page temp file (rust-lang/cargo#16917)
- Fix flaky test: sparse_blocking_count (rust-lang/cargo#16916)
- Fix flaky test compile_offline_while_transitive_dep_not_cached (rust-lang/cargo#16915)
- Fix test fetch_all_platform_dependencies_when_no_target_is_given (rust-lang/cargo#16914)
- chore(ci): Use `actions/deploy-pages` for Cargo Contributor Guide deployment (rust-lang/cargo#16876)
- Convert GitHub fast path to use http_async (rust-lang/cargo#16912)
- refactor(network): convert .crate downloads to use http_async (rust-lang/cargo#16902)
- fix(tests): flaky test local_poll_adapter deferred_success (rust-lang/cargo#16909)

r? ghost
2026-04-21 20:04:46 +00:00
cyrgani
d54b62fdcd rename and move deriving/issue-*.rs 2026-04-21 19:45:01 +00:00
cyrgani
3a6c164d2e cleanup deriving/issue-*.rs 2026-04-21 19:31:26 +00:00
Jonathan Brouwer
79e2ff7d72 Rollup merge of #155590 - GuillaumeGomez:rm-attributelintkind, r=JonathanBrouwer
Remove AttributeLintKind variants - part 5

Part of https://github.com/rust-lang/rust/issues/153099.

r? @JonathanBrouwer
2026-04-21 20:42:53 +02:00
Jonathan Brouwer
aa3335484f Rollup merge of #155547 - aerooneqq:better-disambiguators, r=oli-obk
Use per-parent disambiguators everywhere

This PR addressing the following concerns about per-parent disambiguators (rust-lang/rust#153955):

- DisambiguatorState is removed, PerParentDisambiguatorState is now used everywhere,
- Steals were removed from every per-parent disambiguator in resolver,
- It adds `parent` field in `PerParentDisambiguatorState` in `#[cfg(debug_assertions)]` for asserting that per-parent disambiguator corresponds to the same `LocalDefId` which is passed into `create_def`,
- ~Removes `Disambiguator` trait replacing it with `Disambiguator` enum, with this change we no longer expose `next` method (as trait should be public otherwise the warning will be emitted). It may affect perf in a negative way though.~

~Those changes should not fix perf issues that were [reported](https://github.com/rust-lang/rust/pull/153955#issuecomment-4269223191), perf run that was attempted [before](https://github.com/rust-lang/rust/pull/153955#issuecomment-4214516698) showed much better results. Performance can be probably fixed by removing per-parent disambiguators replacing them with a single one as it was before, then it will be passed to AST -> HIR lowering and modified. For delayed owners we can store ~followup disambiguators as it was in the beginning of the rust-lang/rust#153955~ per-parent disambiguators. This solution should save achievements from rust-lang/rust#153955 (removed `DefPathData` variants).
However, I would prefer to keep per-parent disambiguators as it seems a better architectural solution for me.~

r? @petrochenkov
cc @oli-obk
2026-04-21 20:42:52 +02:00
Jonathan Brouwer
63b6bd933e Rollup merge of #155425 - nnethercote:rm-dup-Flags-methods, r=nikomatsakis
Remove duplicated `Flags` methods.

The `Flags` trait has two methods: `flags` and `outer_exclusive_binder`. Multiple types impl this trait and then also have duplicate inherent methods with the same names; these are all marked with "Think about removing this" comments. This is left over from things being moved into `rustc_type_ir`.

This commit removes those inherent methods. This requires adding `use Flags` to a number of files.

r? @lcnr
2026-04-21 20:42:51 +02:00
Jonathan Brouwer
65fcd87abd Rollup merge of #152834 - lapla-cogito:issue_152831, r=jackh726
Fix incorrect `let` to `const` suggestion for pattern bindings

When a variable from a pattern binding was referenced inside a `const {}` block, the compiler incorrectly suggested replacing `let` with `const`. This was reported in rust-lang/rust#152831 for `if let`, but also applies to `while let` and `let ... else`.
2026-04-21 20:42:51 +02:00
Jonathan Brouwer
5abe5ea630 Rollup merge of #155546 - Unique-Usman:ua/impl_traits, r=estebank
Improve E0308 error message for `impl Trait` return mismatches

When a function returns `impl Trait`, all branches must return the same concrete type. Previously, the compiler showed:

    expected `First` because of return type

This was misleading, as it suggested the return type was `First`, rather than any single type implementing the trait.

Update the diagnostic to:

    expected a single type implementing `Value` because of return type

Also highlight the first return expression to make it clearer why subsequent returns do not match.
2026-04-21 20:42:50 +02:00
Omnikar
2863ed640f Add missing dyn keyword to trait_alias page of the Unstable Book 2026-04-21 14:16:54 -04:00
Josh Stone
29ccf67f77 rustc_thread_pool: Make CoreLatch::set use SeqCst instead of AcqRel
Every other modification of this variable uses `SeqCst`, which is
justified in the sleep README. This particular choice of `AcqRel` was
not discussed during its addition in rayon-rs/rayon#746, nor
rayon-rs/rfcs#5, so I suspect was simply an oversight from earlier
development. We probably do want this to participate in the same
sequential consistency.

The only other ordering difference is `CoreLatch::probe`'s load with
`Acquire`, which should be fine because this doesn't need consistency
with the sleep counters.

See also rayon-rs/rayon#1297. As I commented there, I think in practice
this would be quite rare to cause any problems, but it *could* be a
source of non-deterministic bugs on targets with weak memory ordering.
2026-04-21 10:41:56 -07:00
Guillaume Gomez
80777dd748 Reorder emails of Guillaume Gomez so it appears as its primary email and not the old one 2026-04-21 19:28:54 +02:00
Guillaume Gomez
940d0f8245 Remove AttributeLintKind::UnknownCrateTypesSuggestion variant 2026-04-21 19:28:53 +02:00
Guillaume Gomez
6b782884e7 Remove AttributeLintKind::DoNotRecommendDoesNotExpectArgs variant 2026-04-21 19:28:46 +02:00
Guillaume Gomez
a9f16fa646 Remove AttributeLintKind::AttrCrateLevelOnly variant 2026-04-21 19:28:34 +02:00
Guillaume Gomez
33b896a067 Remove AttributeLintKind::DocTestLiteral variant 2026-04-21 19:28:27 +02:00
Guillaume Gomez
b1cc9a60d8 Remove AttributeLintKind::DocTestUnknown variant 2026-04-21 19:28:16 +02:00
Guillaume Gomez
2ccad45f29 Remove AttributeLintKind::DocTestTakesList variant 2026-04-21 19:27:21 +02:00
bors
d2f88d4b65 Auto merge of #155599 - JonathanBrouwer:rollup-cI1hRiI, r=JonathanBrouwer
Rollup of 4 pull requests

Successful merges:

 - rust-lang/rust#152611 (Modify error message of importing inherent associated items when `#[feature(import_trait_associated_functions)]` is enabled)
 - rust-lang/rust#155359 (Improperctypes refactor2.2)
 - rust-lang/rust#155036 (Store a PathBuf rather than SerializedModule for cached modules)
 - rust-lang/rust#155554 (add warning message when using x fix)
2026-04-21 16:48:52 +00:00
Alex Crichton
1dea6b8c3b std: Update support for wasm32-wasip3
This commit performs some minor update within the standard library for
the `wasm32-wasip3` target. This target is a tier 3 target currently due
to the WASIp3 specification not being officially released. This commit
adds a dependency from the standard library on the `wasip3` crate in the
same manner as the `wasip1` and `wasip2` crates that it already depends
on. The use-sites, for randomness and environment variables, are then
updated to handle the wasip2/wasip3 multiplexing.
2026-04-21 09:26:25 -07:00
Weihang Lo
14db8ba1cf Update cargo submodule 2026-04-21 12:23:20 -04:00
lapla
90c03d8ff4 Flatten nested tuple destructuring 2026-04-22 00:24:19 +09:00
lapla
a687f0b658 Fix incorrect let to const suggestion for pattern bindings 2026-04-22 00:24:08 +09:00
aerooneqq
2e6a082513 Use per-parent disambiguators 2026-04-21 18:23:40 +03:00
Jonathan Brouwer
e150483f4f Rollup merge of #155554 - nivekithan:issue-155545-fix, r=jyn514
add warning message when using x fix

Fix for issue: https://github.com/rust-lang/rust/issues/155545

Before:
<img width="1880" height="329" alt="image" src="https://github.com/user-attachments/assets/b713d940-f229-4c63-8df8-93634f017793" />

After:
<img width="1897" height="387" alt="image" src="https://github.com/user-attachments/assets/5bbca701-b319-45ca-9d46-39847c50b6f8" />

Text added

```
WARNING: `x fix` is provided on a best-effort basis and does not support all `cargo fix` options correctly.
```
2026-04-21 16:53:40 +02:00
Jonathan Brouwer
8ffe107470 Rollup merge of #155036 - bjorn3:lto_refactors16, r=TaKO8Ki
Store a PathBuf rather than SerializedModule for cached modules

In cg_gcc `ModuleBuffer` already only contains a path anyway. And for moving LTO into `-Zlink-only` we will need to serialize `MaybeLtoModules`. By storing a path cached modules we avoid writing them to the disk a second time during serialization of `MaybeLtoModules`.

Some further improvements will require changes to cg_gcc that I would prefer landing in the cg_gcc repo to actually test the LTO changes in CI.

Part of https://github.com/rust-lang/compiler-team/issues/908
2026-04-21 16:53:39 +02:00
Jonathan Brouwer
f21c57d8c6 Rollup merge of #155359 - niacdoial:improperctypes-refactor2.2, r=petrochenkov
Improperctypes refactor2.2

This is "part 2/3 of 2/3 of 1/2" of the original pull request https://github.com/rust-lang/rust/pull/134697 (refactor plus overhaul of the ImproperCTypes family of lints)
(all pulls of this series of pulls are supersets of the previous pulls.)
previous pull: https://github.com/rust-lang/rust/pull/155358
next pull: https://github.com/rust-lang/rust/pull/146273

This commit splits the lint's `visit_type` function into multiple functions that focus on specific things:
- visit_indirection (references, boxes, raw pointers)
- visit_variant_fields (the list of fields of a struct, enum variant, or union)
- visit_enum
- visit_struct_or_union
- visit_type (most "easy" decisions such as labeling `char` unsafe are here)

since, during these visits, we often move from an "outer type" to an "inner type" (structs, arrays, pointers, etc...),
two structs have been added to track the current state of a visit:
- VisitorState tracks the state related to the "original type" being checked (function argument/return, static variable)
- OuterTyData tracks the data related to the type "immediately outer to the current visited type"

r? petrochenkov (because you asked me to)
2026-04-21 16:53:38 +02:00
Jonathan Brouwer
04dfc2b595 Rollup merge of #152611 - CoCo-Japan-pan:fix-148009, r=jackh726
Modify error message of importing inherent associated items when `#[feature(import_trait_associated_functions)]` is enabled

Fixes rust-lang/rust#148009

This PR improves the diagnostic for importing inherent associated items from a struct or union when
`#[feature(import_trait_associated_functions)]` (rust-lang/rust#134691) is enabled.

Previously, this would result in a "not a module" error. This change provides a more specific error message clarifying that only trait associated items can be imported, while inherent associated items remain ineligible for import.

Enums are currently excluded from this change because their variants are valid import targets and require distinct handling.
2026-04-21 16:53:37 +02:00
Chris Burel
e981edde2b Enable AddressSanitizer on arm-unknown-linux-gnueabihf and armv7-unknown-linux-gnueabihf
Add SanitizerSet::ADDRESS to the supported_sanitizers for the
arm-unknown-linux-gnueabihf and armv7-unknown-linux-gnueabihf targets.

The AddressSanitizer is already enabled on the armv7-linux-androideabi
platform, which shares the same ARM architecture. There is no reason
these Linux GNU targets should not also support it, as the underlying
LLVM support for ASan on 32-bit ARM is already in place.
2026-04-21 09:58:49 -04:00
CoCo-Japan-pan
cbba81e0e2 Add early returns in check_trait_front_matter 2026-04-21 22:55:35 +09:00
Amanjeev Sethi
6f511f1218 Mentions rustc-docs for rustc_private
This was missing from my last PR.
Post-review.
2026-04-21 09:38:44 -04:00
CoCo-Japan-pan
470e4623db Rule out const unsafe impl from FnHeader to
correctly parse `const unsafe trait` implementations.
2026-04-21 22:17:23 +09:00
niacdoial
7bb9851ae8 ImproperCTypes: remove special cases through better state tracking
Another interal change that shouldn't impact rustc users.
Code called outside of `visit_type` (and callees) is moved inside, by
adding new types to properly track the state of a type visitation.
- OuterTyKind tracks the knowledge of the type "directly outside of" the
  one being visited (if we are visiting a struct's field, an array's
  element, etc)
- RootUseFlags tracks the knowledge of how the "original type being
  visited" is used: static variable, function argument/return, etc.
2026-04-21 15:08:51 +02:00
bors
365515367b Auto merge of #155596 - jhpratt:rollup-zyXU16X, r=jhpratt
Rollup of 6 pull requests

Successful merges:

 - rust-lang/rust#155028 (tests: add whitespace tests for vertical tab behavior)
 - rust-lang/rust#155582 (Rewrite `FlatMapInPlace`.)
 - rust-lang/rust#151194 (Fix wrong suggestion for returning async closure)
 - rust-lang/rust#154377 (Fix `#[expect(dead_code)]` liveness propagation)
 - rust-lang/rust#155572 (Move diagnostic attribute target checks from check_attr)
 - rust-lang/rust#155586 (Ensure we don't feed owners from ast lowering if we ever make that query tracked)
2026-04-21 13:03:12 +00:00
Jacob Pratt
b646067bfd Rollup merge of #155586 - oli-obk:assert-ignored-feed, r=petrochenkov
Ensure we don't feed owners from ast lowering if we ever make that query tracked

follow-up to rust-lang/rust#153489

I don't expect this to ever really be an issue, but better safe than sorry 😆
2026-04-21 08:22:17 -04:00
Jacob Pratt
02fc33b679 Rollup merge of #155572 - mejrs:move_target_checks, r=JonathanBrouwer,GuillaumeGomez
Move diagnostic attribute target checks from check_attr

Move diagnostic attribute target checks into their targets. Part of https://github.com/rust-lang/rust/issues/131229#issuecomment-3959910413

This is much easier with `emit_dyn_lint` :) (thanks @GuillaumeGomez !)

I think there might be some opportunity to simplify all these `check_diagnostic_*` methods in `check_attr`. However there are some diagnostic attribute prs in flight and I'd like to wait for those to land first and then think about it. So that PR is not for today.

r? @JonathanBrouwer (or @GuillaumeGomez if you want)
2026-04-21 08:22:17 -04:00
Jacob Pratt
3b4c17915e Rollup merge of #154377 - mu001999-contrib:fix/dead-code, r=TaKO8Ki
Fix `#[expect(dead_code)]` liveness propagation

Fixes https://github.com/rust-lang/rust/issues/154324
Fixes https://github.com/rust-lang/rust/issues/152370 (cc @eggyal)

Previously, when traversing from a `ComesFromAllowExpect::Yes` item (i.e., with `#[allow(dead_code)]` or `#[expect(dead_code)]`), other `ComesFromAllowExpect::Yes` items reached during propagation would be updated to `ComesFromAllowExpect::No` and inserted into `live_symbols`. That caused `dead_code` lint couldn't be emitted correctly.

After this PR, `ComesFromAllowExpect::Yes` items no longer incorrectly update other `ComesFromAllowExpect::Yes` items during propagation or mark them live by mistake, then `dead_code` lint could behave as expected.
2026-04-21 08:22:16 -04:00
Jacob Pratt
545e7dc06c Rollup merge of #151194 - chenyukang:yukang-fix-150701-async-closure, r=wesleywiser
Fix wrong suggestion for returning async closure

Fixes rust-lang/rust#150701

r? @estebank
2026-04-21 08:22:15 -04:00
Jacob Pratt
eb2c80dabe Rollup merge of #155582 - nnethercote:overhaul-flat_map_in_place, r=chenyukang
Rewrite `FlatMapInPlace`.

Replace the hacky macro with a generic function and a new `FlatMapInPlaceVec` trait. More verbose but more readable and typical.

LLM disclosure: I asked Claude Code to critique this file and it suggested the generic function + trait idea. I implemented the idea entirely by hand.

r? @chenyukang
2026-04-21 08:22:14 -04:00
Jacob Pratt
2c1f01728d Rollup merge of #155028 - Brace1000:whitespace-tests, r=chenyukang
tests: add whitespace tests for vertical tab behavior

This PR adds two small tests to highlight how vertical tab (\x0B)
is handled differently across Rust's whitespace definitions.

The Rust lexer treats vertical tab as whitespace (Unicode
Pattern_White_Space), while `split_ascii_whitespace` follows the
WhatWG Infra Standard and does not include vertical tab.

These tests make that difference visible and easier to understand.

See: https://github.com/rustfoundation/interop-initiative/issues/53
2026-04-21 08:22:14 -04:00
Brian Oiko
c2c486a3c0 tests: add whitespace tests for vertical tab behavior
* tests: add whitespace tests for vertical tab behavior

Add two small tests to highlight how vertical tab is handled differently.

- vertical_tab_lexer.rs checks that the lexer treats vertical tab as whitespace
- ascii_whitespace_excludes_vertical_tab.rs shows that split_ascii_whitespace does not split on it

This helps document the difference between the Rust parser (which accepts vertical tab)
and the standard library’s ASCII whitespace handling.

See: rust-lang/rust-project-goals#53
* tests: add ignore-tidy-tab directive to whitespace tests
* tests: expand vertical tab lexer test to cover all Pattern_White_Space chars
* tests: add whitespace/ README entry explaining lexer vs stdlib mismatch
* Update ascii_whitespace_excludes_vertical_tab.rs
* Update ascii_whitespace_excludes_vertical_tab.rs

make sure tabs and spaces are well checked
* Update ascii_whitespace_excludes_vertical_tab.rs
* fix tidy: add whitespace README entry
* Update README.md with missing full stop
* Update ascii_whitespace_excludes_vertical_tab.rs
* fix tidy: use full path format for whitespace README entry
* fix tidy: README order, trailing newlines in whitespace tests
* fix: add run-pass directive and restore embedded whitespace bytes
* fix tidy: remove duplicate whitespace README entry
* 

Add failing UI test for invalid whitespace (zero width space)

This adds a //@ check-fail test to ensure that disallowed whitespace
characters like ZERO WIDTH SPACE are rejected by the Rust lexer.
* git add tests/ui/whitespace/invalid_whitespace.rs
git commit -m "Fix tidy: add trailing newline"
git push
* Fix tidy: add trailing newline
* Update invalid_whitespace.rs
* Update invalid_whitespace.rs
* Clean up whitespace in invalid_whitespace.rs

Remove unnecessary blank lines in invalid_whitespace.rs
* Update invalid_whitespace.rs
* Clarify ZERO WIDTH SPACE usage in test

Update comment to clarify usage of ZERO WIDTH SPACE.
* Improve error messages for invalid whitespace

Updated error messages to clarify the issue with invisible characters.
* Modify invalid_whitespace test for clarity

Update test to check for invalid whitespace characters.
* Resolve unknown token error in invalid_whitespace.rs

Fix whitespace issue causing unknown token error.
* Remove invisible character from variable assignment

Fix invisible character issue in variable assignment.
* Improve error message for invalid whitespace

Updated error message to clarify invisible characters.
* Improve error handling for invisible characters

Updated error message for invisible characters in code.
* Document error for unknown token due to whitespace

Add error message for invalid whitespace in code
* Update error message for invalid whitespace handling
* Modify invalid_whitespace.rs for whitespace checks

Updated the test to check for invalid whitespace handling.
* Correct whitespace in variable declaration

Fix formatting issue by adding space around '=' in variable declaration.
* Update error message for invalid whitespace
* Update invalid_whitespace.stderr
* Refine error handling for invalid whitespace test

Update the error messages for invalid whitespace in the test.
* Update invalid_whitespace.rs
* Fix whitespace issues in invalid_whitespace.rs
* Update invalid_whitespace.stderr file
* Clean up whitespace in invalid_whitespace.rs

Removed unnecessary blank lines from the test file.
* Update invalid_whitespace.stderr
2026-04-21 12:20:19 +00:00
Marco Ieni
c9711095bc Merge pull request #2843 from marcoieni/document-public-dashboard--again
document public dashboard (again)
2026-04-21 13:28:14 +02:00
MarcoIeni
9af3d2cc14 document public dashboard (again) 2026-04-21 13:24:14 +02:00
cyrgani
90e64771d5 merge trivial Clone tests 2026-04-21 10:53:04 +00:00
cyrgani
968ff5e331 remove and rename two deriving-bounds.rs tests 2026-04-21 10:50:12 +00:00
Waffle Lapkin
be8bfb2d69 x fmt
I have no idea what caused this change, I don't think other commits
changed anything near these lines?..
2026-04-21 12:42:52 +02:00
Waffle Lapkin
54abf6d683 remove unused parameter from opt_alias_variances 2026-04-21 12:28:26 +02:00
Waffle Lapkin
e8b6c9737e fix ty::UnevaluatedConst<I>>->AliasTerm<I> conversion 2026-04-21 12:28:25 +02:00
Waffle Lapkin
59be02e594 bless ui tests 2026-04-21 12:28:25 +02:00
Waffle Lapkin
0ff2fe8eef add AliasTermTy::with_args to simplify a common-ish pattern 2026-04-21 12:28:24 +02:00
Waffle Lapkin
c32020d547 AliasTermTy refactor: fixup clippy 2026-04-21 12:28:23 +02:00
Waffle Lapkin
c0ddfb0ec3 AliasTermTy refactor: fixup rustdoc 2026-04-21 12:28:23 +02:00
Waffle Lapkin
d7986943e4 AliasTermTy refactor: fixup compiler 2026-04-21 12:28:22 +02:00
Waffle Lapkin
3484c89c0b AliasTermTy refactor: API changes 2026-04-21 12:28:21 +02:00
mejrs
3990dda860 say "implementation(s) in "not on trait impl" lints 2026-04-21 11:30:14 +02:00
mejrs
80fb0aa44e Move diagnostic::do_not_recommend target checking 2026-04-21 11:30:00 +02:00
mejrs
c62be6e992 Move diagnostic::on_unknown target check 2026-04-21 11:30:00 +02:00
mejrs
59503ecb5e Move diagnostic::on_unimplemented target check 2026-04-21 11:30:00 +02:00
mejrs
26d2c30682 Move diagnostic::on_move target check 2026-04-21 11:29:59 +02:00
mejrs
5ba06cccd0 Always refer to non-const trait impls 2026-04-21 11:29:58 +02:00
mejrs
39f517fd18 Move diagnostic::on_const target check 2026-04-21 11:29:41 +02:00
bors
93637f398f Auto merge of #155583 - jhpratt:rollup-HPCle0C, r=jhpratt
Rollup of 5 pull requests

Successful merges:

 - rust-lang/rust#155532 (Fix redundant boolean comparison in `Mutex::try_lock`)
 - rust-lang/rust#155558 (Clarify that isqrt returns the principal (non-negative) square root)
 - rust-lang/rust#155559 (add safety doc (section header) to two unsafe methods in `NonZero`)
 - rust-lang/rust#155564 (Implement const Default for &CStr)
 - rust-lang/rust#155565 (constify `Vec` comparisons)
2026-04-21 08:59:12 +00:00
Redddy
0c97aba201 Merge pull request rust-lang/rustc-dev-guide#2830 from DanielEScherzer/new-features-params
implementing-new-features.md: update parameters to `declare_features!`
2026-04-21 16:46:16 +09:00
Benno Lossin
a041a76097 field representing types: add test for unsized types 2026-04-21 09:29:34 +02:00
Benno Lossin
ca700edee3 field representing types: test all implemented traits 2026-04-21 09:29:10 +02:00
Benno Lossin
104914e614 field representing types: implement Hash, Eq & Ord 2026-04-21 09:28:53 +02:00
Benno Lossin
f3719b1686 field representing types: implement Default 2026-04-21 09:27:55 +02:00
Benno Lossin
59f18c21b0 field representing types: implement Debug through reflection
Using the reflection experiment, we can print the actual names of the
field that an FRT is referring to. In case this breaks, there is an
alternative implementation in the note comment.
2026-04-21 09:22:28 +02:00
Benno Lossin
2c79213bc5 field representing types: remove explicit Send and Sync impls
Commit cb37ee2c87 ("make field representing types invariant over the
base type") made the auto-trait impl work even if `T: !Send` or `T:
!Sync` thus we can remove these explicit unsafe impls while FRTs still
implement `Send` and `Sync`.
2026-04-21 09:20:02 +02:00
Tshepang Mbambo
2d2894c3d1 Merge pull request #2842 from rust-lang/rustc-pull
Rustc pull update
2026-04-21 08:58:57 +02:00
Oli Scherer
b1c7595965 Ensure we don't feed owners from ast lowering if we ever make that query tracked 2026-04-21 08:56:02 +02:00
The rustc-josh-sync Cronjob Bot
6fe2465770 Merge ref '84c119007247' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@84c1190072
Filtered ref: rust-lang/rustc-dev-guide@9762b35681
Upstream diff: d12e1e12ae...84c1190072

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-21 06:54:03 +00:00
The rustc-josh-sync Cronjob Bot
babfcd8cec Prepare for merging from rust-lang/rust
This updates the rust-version file to 84c1190072.
2026-04-21 06:53:59 +00:00
Jacob Pratt
b4bab32075 Rollup merge of #155565 - Lars-Schumann:const-vec-cmp, r=jhpratt
constify `Vec` comparisons

Tracking Issue: https://github.com/rust-lang/rust/issues/143800

Due to `Cow` not implementing `const Deref` (https://github.com/rust-lang/rust/issues/147964), the comparisons including a `Cow` were not constified.
2026-04-21 02:20:28 -04:00
Jacob Pratt
53b9b9a108 Rollup merge of #155564 - tshakalekholoane:tshaka/const_default/cstr, r=jhpratt
Implement const Default for &CStr

Implements `const Default` for `&CStr`.

Tracking issue: rust-lang/rust#143894.
2026-04-21 02:20:27 -04:00
Jacob Pratt
64b897180d Rollup merge of #155559 - safer-rust:fix-doc2, r=jhpratt
add safety doc (section header) to two unsafe methods in `NonZero`

This PR adds a Safety section to two unsafe methods in `NonZero`:
- [unchecked_add](https://doc.rust-lang.org/nightly/core/num/struct.NonZero.html#method.unchecked_add)
- [unchecked_mul](https://doc.rust-lang.org/nightly/core/num/struct.NonZero.html#method.unchecked_mul)

The safety documentation is now consistent with that of [`u8::unchecked_add`](https://doc.rust-lang.org/nightly/core/primitive.u8.html#method.unchecked_add) and [`u8::unchecked_mul`](https://doc.rust-lang.org/nightly/core/primitive.u8.html#method.unchecked_mul).
2026-04-21 02:20:26 -04:00
Jacob Pratt
156cc9fb23 Rollup merge of #155558 - nivekithan:issue-154000-fix, r=jhpratt
Clarify that isqrt returns the principal (non-negative) square root

Clarify which root is returned from `isqrt` and `checked_isqrt`

Fixes: https://github.com/rust-lang/rust/issues/154000
Previous PRs: https://github.com/rust-lang/rust/pull/154462
2026-04-21 02:20:26 -04:00
Jacob Pratt
387df6efb1 Rollup merge of #155532 - StepfenShawn:patch-1, r=jhpratt
Fix redundant boolean comparison in `Mutex::try_lock`

Simplify boolean return in `Mutex::try_lock`.
Replace `expr == false` with `!expr` for cleaner code.
2026-04-21 02:20:25 -04:00
Nicholas Nethercote
21cd762cd1 Rewrite FlatMapInPlace.
Replace the hacky macro with a generic function and a new
`FlatMapInPlaceVec` trait. More verbose but more readable and typical.

LLM disclosure: I asked Claude Code to critique this file and it
suggested the generic function + trait idea. I implemented the idea
entirely by hand.
2026-04-21 15:52:55 +10:00
bors
9ab01ae53c Auto merge of #155491 - ohadravid:faster-storage-in-copyprop-and-gvn, r=saethlin
Fix performance regression introduced in #142531 by excluding `Storage{Live,Dead}` from CGU size estimation



Fix performance regression introduced in rust-lang/rust#142531 ([rust-timer comment](https://github.com/rust-lang/rust/pull/142531#issuecomment-4273712294)) by excluding `Storage{Live,Dead}` from CGU size estimation.

Also, avoid unneeded work for storage removal in non-opt builds in CopyProp and GVN
by allocating local sets for the storage accounting only when `tcx.sess.emit_lifetime_markers()`. 

r? saethlin
2026-04-21 05:35:16 +00:00
Chris Denton
a6ec2947a3 Explicitly note that we're leaking a handle 2026-04-21 04:25:35 +00:00
John Kåre Alsaker
0add85cbe6 Remove nodes_in_current_session field and related assertions 2026-04-21 05:05:44 +02:00
Josiah Glosson
6f28cd5073 Make Rcs and Arcs use pointer comparison for unsized types 2026-04-20 21:48:58 -05:00
bors
84c1190072 Auto merge of #155576 - jhpratt:rollup-F5kv4Uy, r=jhpratt
Rollup of 5 pull requests

Successful merges:

 - rust-lang/rust#153411 (Offload slice support)
 - rust-lang/rust#154557 (Make E0284 generic argument suggestions more explicit)
 - rust-lang/rust#154933 (Suggest removing `&` when awaiting a reference to a future)
 - rust-lang/rust#155524 (Fix LLVM offload install docs to use semicolon-separated CMake lists)
 - rust-lang/rust#155568 (Update books)
2026-04-21 02:16:22 +00:00
Jacob Pratt
c7ccec1549 Rollup merge of #155568 - rustbot:docs-update, r=ehuss
Update books

## rust-embedded/book

2 commits in 2463edeb8003c5743918b3739a9f6870b86396f5..0789b0f29e73ecb91213cac10ad0eec1b9333770
2026-04-11 08:46:22 UTC to 2026-04-10 14:01:38 UTC

- remove IO chapter, is covered in next chapter (rust-embedded/book#411)
- add embassy chapter (rust-embedded/book#412)

## rust-lang/reference

10 commits in d2715c07e9dd9839c0c7675ecfa18bec539a6ee9..8c88f9d0bdd75ffdc0691676d83212ae22a18cee
2026-04-20 15:20:24 UTC to 2026-04-07 16:25:09 UTC

- typo in example code (rust-lang/reference#2232)
- oxford comma (rust-lang/reference#2233)
- improve readability (rust-lang/reference#2234)
- typo (rust-lang/reference#2230)
- Clarify items.fn.generics.param-bounds (rust-lang/reference#2229)
- follow formatting style guideline (rust-lang/reference#2228)
- Update `derive` export locations (rust-lang/reference#2223)
- Clarify that `{self}` imports require a module parent (rust-lang/reference#2221)
- stabilize s390x vector registers (rust-lang/reference#2215)
- Fix misuse of *usage* throughout the Reference (rust-lang/reference#2222)

## rust-lang/rust-by-example

2 commits in b31e3b8da01eeba0460f86a52a55af82709fadf5..898f0ac1479223d332309e0fce88d44b39927d28
2026-04-19 11:40:28 UTC to 2026-04-19 11:38:45 UTC

- remove debug printing for the u32 and bool in variable_bindings.md (rust-lang/rust-by-example#1999)
- Update for.md (rust-lang/rust-by-example#2008)
2026-04-20 20:50:23 -04:00
Jacob Pratt
adce5da870 Rollup merge of #155524 - sharesth23:fixing-llvm-doc, r=ZuseZ4
Fix LLVM offload install docs to use semicolon-separated CMake lists

Update  so the LLVM CMake example uses  and , which is the correct list separator syntax for LLVM CMake options.[Docs] Remove shortcode from models page heading
2026-04-20 20:50:22 -04:00
Jacob Pratt
03dc6a3a28 Rollup merge of #154933 - fru1tworld:fix-87211-ref-future-diagnostic, r=chenyukang
Suggest removing `&` when awaiting a reference to a future

Fixes rust-lang/rust#87211

When `.await`ing `&impl Future`, suggest removing the `&` instead of removing `.await`.
2026-04-20 20:50:22 -04:00
Jacob Pratt
a8e1664fd8 Rollup merge of #154557 - Muhtasim-Rasheed:issue-147313-improve-help, r=chenyukang
Make E0284 generic argument suggestions more explicit

Closes rust-lang/rust#147313

Previously, when type annotations were missing for a function call, rust suggested: "consider specifying the generic argument". This PR improves the diagnostics:

- If only one generic type is missing:
  "consider specifying a concrete type for the generic type `<T>`" with the turbofish being "::\<SomeConcreteType>"
- If only one const generic is missing:
  "consider specifying a const for the const generic `<CONST>`" with the turbofish being "::<SOME_CONST>"

Multiple missing generics still produce the original more general suggestion
2026-04-20 20:50:21 -04:00
Jacob Pratt
4c7e6565ef Rollup merge of #153411 - Sa4dUs:offload-slices, r=ZuseZ4
Offload slice support

This PR allows offload to support slice type arguments.

~NOTE: this is built on top of https://github.com/rust-lang/rust/pull/152283~

r? @ZuseZ4
2026-04-20 20:50:20 -04:00
bors
4fbae3e309 Auto merge of #154945 - oli-obk:merge-visitors-def-collector-brg, r=petrochenkov
Merge BuildReducedGraphVisitor into DefPathVisitor

These two visitors run right after each other on the same immutable AST. There's also a hash map for transferring the TyCtxtFeed created in the def collector to the BRG when it visits the same items. There are possibly more avenues for sharing logic, but I want to keep this PR simple.

only opening for perf runs for now. I'm still investigating how to ensure that future changes don't introduce subtle bugs by forgetting that def collection and reduced graph building are one pass now

Best reviewed commit-by-commit. I took a lot of care for making the individual changes reviewable, but all the `Merge *` commits aren't able to compile libcore until the last one.
2026-04-20 23:10:06 +00:00
Zac Harrold
7653e5ea01 Move RawOsError to core::io 2026-04-21 09:04:58 +10:00
Zac Harrold
4cb72b3ca5 Adjust Usage of RawOsError
Inconsistently referenced through `std::sys` and `std::io`. Choosing `std::io` as the canonical source to make migration to `core::io` cleaner.
2026-04-21 09:03:32 +10:00
Zac Harrold
e1ef601a73 Adjust Documentation for RawOsError
The hyperlink to `std::io::Error` will not be valid when moved to `core::io`.
There is also a typo which I might as well fix while I'm here.
2026-04-21 09:03:32 +10:00
niacdoial
6dfa52ca93 ImproperCTypes: regroup Box/Ptr/Ref logic
Another interal change that shouldn't impact rustc users.
This time, regroup into `visit_indirections` the code dealing with the
FFI safety of Boxes, Refs and RawPtrs.
2026-04-21 00:50:25 +02:00
niacdoial
d75c93dad2 ImproperCTypes: reorder simple type checks
Another interal change that shouldn't impact rustc users.
the list of simpler type-based decisions made by `visit_type` are
reordered and are given better documentation.
2026-04-21 00:50:25 +02:00
niacdoial
05d6cdb52c ImproperCTypes: move ADT logic into separate visit_ methods
Another interal change that shouldn't impact rustc users.
The goal (of this commit and a few afterwards) is to break apart the gigantic
visit_type function into more managable and easily-editable bits that focus
on specific parts of FFI safety.
For now, we break the code specific to enums one side, and
structs/unions on the other, into separate visit_? methods
2026-04-21 00:50:25 +02:00
Eric Huss
69dae5941e Update shebang reference rule names
This updates the rule names for shebang which were changed in
rust-lang/reference#2192 and rust-lang/reference#2199.
2026-04-20 15:08:37 -07:00
bors
66da6cae1a Auto merge of #155567 - JonathanBrouwer:rollup-0zpjwMk, r=JonathanBrouwer
Rollup of 7 pull requests

Successful merges:

 - rust-lang/rust#155556 (`rust-analyzer` subtree update)
 - rust-lang/rust#152162 (Suggest returning a reference for unsized place from a closure)
 - rust-lang/rust#155389 (Simplify macros for target-modifier and mitigation flags)
 - rust-lang/rust#155553 (miri subtree update)
 - rust-lang/rust#153546 (tests/ui/extern: add annotations for reference rules)
 - rust-lang/rust#155475 (Make reparsed guard metavars collect tokens)
 - rust-lang/rust#155560 (Remove `AttributeLintKind` variants - part 4)
2026-04-20 19:35:12 +00:00
Marcelo Domínguez
af839a8a96 Add offload slice support 2026-04-20 19:15:52 +02:00
rustbot
231acce8cc Update books 2026-04-20 19:00:33 +02:00
Jonathan Brouwer
ca0710af53 Rollup merge of #155560 - GuillaumeGomez:rm-attributelintkind, r=JonathanBrouwer
Remove `AttributeLintKind` variants - part 4

Part of https://github.com/rust-lang/rust/issues/153099.

r? @JonathanBrouwer
2026-04-20 18:57:04 +02:00
Jonathan Brouwer
13b537002b Rollup merge of #155475 - cijiugechu:missing-tokens, r=jieyouxu
Make reparsed guard metavars collect tokens

This should avoid missing tokens.

Closes rust-lang/rust#155333
2026-04-20 18:57:03 +02:00
Jonathan Brouwer
caa265ec8b Rollup merge of #153546 - DanielEScherzer:test-references-extern, r=ehuss
tests/ui/extern: add annotations for reference rules
2026-04-20 18:57:03 +02:00
Jonathan Brouwer
1b64473ea4 Rollup merge of #155553 - RalfJung:miri, r=RalfJung
miri subtree update

Subtree update of `miri` to 16dd940bb9.

Created using https://github.com/rust-lang/josh-sync.

r? @ghost
2026-04-20 18:57:02 +02:00
Jonathan Brouwer
074ed7b651 Rollup merge of #155389 - Zalathar:flag-macros, r=mati865
Simplify macros for target-modifier and mitigation flags

- Rebased and revised version of https://github.com/rust-lang/rust/pull/154501.
---

The macros used for handling command-line flags that are “target modifiers” or “mitigations” are quite complicated, and can be significantly simplified by tweaking their syntax and by making use of `${ignore(..)}` metavars.

It's possible that more code could be moved out of macros (e.g. declaring some of the enums by hand), but that can be investigated in a potential follow-up.

There should be no change to compiler behaviour.
2026-04-20 18:57:01 +02:00
Jonathan Brouwer
515c670b35 Rollup merge of #152162 - chenyukang:yukang-fix-152064-unsized-closure-return, r=petrochenkov
Suggest returning a reference for unsized place from a closure

Fixes rust-lang/rust#152064

There are 3 similar note:
`the size for values of type str cannot be known at compilation time`
for different spans, maybe need more work to remove some of them.

This PR only adds a suggestion for using a reference.
2026-04-20 18:57:00 +02:00
Jonathan Brouwer
64d875f6c2 Rollup merge of #155556 - lnicola:sync-from-ra, r=lnicola
`rust-analyzer` subtree update

Subtree update of `rust-analyzer` to cc5bc48b25.

Created using https://github.com/rust-lang/josh-sync.

r? @ghost
2026-04-20 18:56:59 +02:00
bors
c28e303778 Auto merge of #155552 - JonathanBrouwer:rollup-JKIpTuW, r=JonathanBrouwer
Rollup of 11 pull requests

Successful merges:

 - rust-lang/rust#154654 (Move `std::io::ErrorKind` to `core::io`)
 - rust-lang/rust#145270 (Fix an ICE observed with an explicit tail-call in a default trait method)
 - rust-lang/rust#154895 (borrowck: Apply `user_arg_index` nomenclature more broadly)
 - rust-lang/rust#155213 (resolve: Make sure visibilities of import declarations make sense)
 - rust-lang/rust#155346 (`single_use_lifetimes`: respect `anonymous_lifetime_in_impl_trait`)
 - rust-lang/rust#155517 (Add a test for Mach-O `#[link_section]` API inherited from LLVM)
 - rust-lang/rust#155549 (Remove some unnecessary lifetimes.)
 - rust-lang/rust#154248 (resolve :  mark repr_simd as internal)
 - rust-lang/rust#154772 (slightly optimize the `non-camel-case-types` lint)
 - rust-lang/rust#155541 (Add `#[rust_analyzer::prefer_underscore_import]` to the traits in `rustc_type_ir::inherent`)
 - rust-lang/rust#155544 (bootstrap: Make "detected modifications" for download-rustc less verbose)
2026-04-20 16:15:13 +00:00
Lars Schumann
2ba7b3b537 constify vec comparisons 2026-04-20 16:00:18 +00:00
Tshaka Lekholoane
339a2f0ba0 Implement const Default for &CStr 2026-04-20 17:40:30 +02:00
Guillaume Gomez
ea690c3d7b Remove AttributeLintKind::DocAutoCfgWrongLiteral variant 2026-04-20 16:59:14 +02:00
Guillaume Gomez
1aee0e07b4 Remove AttributeLintKind::DocUnknownAny variant 2026-04-20 16:54:15 +02:00
Guillaume Gomez
0ad35a24fd Remove AttributeLintKind::DocUnknownPlugins variant 2026-04-20 16:49:55 +02:00
aisr
0bfdb18855 add safety sections to two unsafe methods in NonZero 2026-04-20 22:46:10 +08:00
Guillaume Gomez
7007737f11 Remove AttributeLintKind::DocUnknownPasses variant 2026-04-20 16:46:06 +02:00
Guillaume Gomez
1e57ed26db Remove AttributeLintKind::DocUnknownSpotlight variant 2026-04-20 16:46:06 +02:00
cijiugechu
ffcbfc1cf4 Use singular wording for single _ placeholders in type suggestions 2026-04-20 22:21:51 +08:00
Tshepang Mbambo
02e975b8ca Merge pull request #2841 from rust-lang/rustc-pull
Rustc pull update
2026-04-20 15:29:30 +02:00
Nivekithan
6b8cb42ee3 update doc to be more clear 2026-04-20 18:55:05 +05:30
The rustc-josh-sync Cronjob Bot
5a7193da12 Merge ref 'd12e1e12ae6f' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@d12e1e12ae
Filtered ref: rust-lang/rustc-dev-guide@f2b52d051c
Upstream diff: e22c616e4e...d12e1e12ae

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-20 13:01:20 +00:00
The rustc-josh-sync Cronjob Bot
ae92374ad5 Prepare for merging from rust-lang/rust
This updates the rust-version file to d12e1e12ae.
2026-04-20 13:01:17 +00:00
bors
91367b0f73 Auto merge of #154924 - nnethercote:rm-impl-HashStable-for-Attr-slice, r=JonathanBrouwer
Remove `HashStable` impl for `[hir::Attribute]`.



This impl skips:
- All doc comments
- A handful of other attributes, mostly `rustc_*` ones related to incremental compilation testing.
    
This skipping originated in rust-lang/rust#36025 and was extended a couple of times, e.g. in rust-lang/rust#36370. Those PRs don't have any explanation of why the skipping exists. Perhaps the reasoning was that doc comments should only affect rustdoc and rustdoc doesn't use incremental compilation? But doc comments end up in metadata, and there is a query `attrs_for_def` that returns a `&'tcx [hir::Attribute]`. So skipping some attributes just seems plainly wrong.
    
This commit removes the impl, which means `[hir::Attribute]` hashing falls back to the default impl for `[T]`. This has no noticeable effect on the test suite. It does slightly hurt performance, because of the doc comments. This perf regression seems worth it for the correctness benefits.
2026-04-20 12:55:41 +00:00
Nivekithan
440ed80b31 add warning message when using x fix 2026-04-20 18:07:13 +05:30
Chayim Refael Friedman
5d84f89497 Merge pull request #22101 from ChayimFriedman2/port-infer-call
fix: Port call expr type checking and closure upvar inference from rustc
2026-04-20 12:01:40 +00:00
Oli Scherer
f2c79f3fc6 Handle attributes entirely in the def collector 2026-04-20 13:56:30 +02:00
Oli Scherer
c8862c74b2 Avoid matching on the assoc item kind twice 2026-04-20 13:56:30 +02:00
Oli Scherer
e61773669a Inline macro calls in assoc item position logic 2026-04-20 13:56:30 +02:00
Oli Scherer
690df236c2 Deduplicate the expansion field between def collection and brg 2026-04-20 13:56:30 +02:00
Oli Scherer
095f11c9ec Inline the now-trivial build_reduced_graph into its sole caller 2026-04-20 13:56:30 +02:00
Oli Scherer
0a714a26a5 Fix use trees 2026-04-20 13:53:15 +02:00
Chayim Refael Friedman
d7f95de6d8 Port call expr type checking and closure upvar inference from rustc 2026-04-20 14:53:10 +03:00
Jonathan Brouwer
02dda7315a Rollup merge of #155544 - jyn514:download-rustc-verbosity, r=jieyouxu
bootstrap: Make "detected modifications" for download-rustc less verbose

cc https://rust-lang.zulipchat.com/#narrow/channel/326414-t-infra.2Fbootstrap/topic/bootstrap.20lists.20all.20files.20I.20change/with/585991706, @RalfJung

r? @jieyouxu
2026-04-20 13:52:09 +02:00
Jonathan Brouwer
26f457a114 Rollup merge of #155541 - ChayimFriedman2:import-underscore, r=TaKO8Ki
Add `#[rust_analyzer::prefer_underscore_import]` to the traits in `rustc_type_ir::inherent`

This is a new attribute (https://github.com/rust-lang/rust-analyzer/pull/21740) that instructs rust-analyzer to prefer importing the trait `as _`. It is useful for these traits since their names often clashes with the type.
2026-04-20 13:52:09 +02:00
Jonathan Brouwer
c4f995c1ba Rollup merge of #154772 - llogiq:nonstandard-style-perf, r=adwinwhite
slightly optimize the `non-camel-case-types` lint

This is just removing a needless `collect()` and a bit of simplification.
2026-04-20 13:52:08 +02:00
Jonathan Brouwer
7162558809 Rollup merge of #154248 - lms0806:issue_154034, r=TaKO8Ki
resolve :  mark repr_simd as internal

I changed ```repr_simd``` to ```internal``` and changed the position to ```feature-group-start: internal feature gates```.

close rust-lang/rust#154034
2026-04-20 13:52:07 +02:00
Jonathan Brouwer
eceed7c1c2 Rollup merge of #155549 - nnethercote:rm-lifetimes, r=JohnTitor
Remove some unnecessary lifetimes.

We have a number of structs with more lifetimes than necessary. This commit removes them.

LLM disclosure: I asked Claude Code to check for unnecessary lifetimes in all types with three or more lifetimes, and it produced a list of candidates (half of which were invalid). I did the modifications for the valid cases myself, and found a couple more cases along the way.

r? @JohnTitor
2026-04-20 13:52:07 +02:00
Jonathan Brouwer
356fdf02ca Rollup merge of #155517 - madsmtm:test-macho-link-section-attrs, r=bjorn3
Add a test for Mach-O `#[link_section]` API inherited from LLVM

The format of the `#[link_section]` attribute is under-documented, but on Mach-O, I think it's roughly the following BNF:
```
LinkSection -> Segment `,` Section (`,` (SectionType (`,` (SectionAttributes)?)?)?)?
Segment -> <0 to 16 bytes>
Section -> <0 to 16 bytes>
SectionType -> `regular` | `zerofill` | `cstring_literals` | `4byte_literals` | `8byte_literals` | `literal_pointers` | `non_lazy_symbol_pointers` | `lazy_symbol_pointers` | `symbol_stubs` | `mod_init_funcs` | `mod_term_funcs` | `coalesced` | `interposing` | `16byte_literals` | `thread_local_regular` | `thread_local_zerofill` | `thread_local_variables` | `thread_local_variable_pointers` | `thread_local_init_function_pointers`
SectionAttributes -> SectionAttribute (`+` SectionAttribute)*
SectionAttribute -> `pure_instructions` | `no_toc` | `strip_static_syms` | `no_dead_strip` | `live_support`, `self_modifying_code` | `debug`
```

This PR adds a small test for a little part of this.

Once https://github.com/rust-lang/rust/issues/154429 is resolved, this should make it possible to test https://github.com/rust-lang/rustc_codegen_cranelift/pull/1648 end-to-end.

r? bjorn3
2026-04-20 13:52:06 +02:00
Jonathan Brouwer
1d9b32a5ac Rollup merge of #155346 - GrigorenkoPV:single-use-lifetimes, r=jdonszelmann
`single_use_lifetimes`: respect `anonymous_lifetime_in_impl_trait`

Tracking issue: rust-lang/rust#44752 (for the `single_use_lifetimes` lint; the `anonymous_lifetime_in_impl_trait` feature seems to have no tracking issue).

Closes rust-lang/rust#129255
Closes rust-lang/rust#135550

@rustbot label A-diagnostics A-lifetimes A-lints D-incorrect L-single_use_lifetimes
2026-04-20 13:52:05 +02:00
Jonathan Brouwer
d83994951d Rollup merge of #155213 - petrochenkov:importvis, r=mu001999
resolve: Make sure visibilities of import declarations make sense

That they are all ordered inside the module and not more private than the module itself.

The `import_decl_vis` logic is also reused when reporting `ambiguous_import_visibilities` lint.
Some asserts are hardened.
Some relevant tests are added.

Extracted from https://github.com/rust-lang/rust/pull/154149.
2026-04-20 13:52:05 +02:00
Jonathan Brouwer
6245e371b9 Rollup merge of #154895 - Enselic:user-arg-index, r=jdonszelmann
borrowck: Apply `user_arg_index` nomenclature more broadly

No change in behavior. Only renames and a couple of added comments.

As requested here: https://github.com/rust-lang/rust/pull/154674#discussion_r3027381648

r? jdonszelmann
2026-04-20 13:52:04 +02:00
Jonathan Brouwer
3530d82c31 Rollup merge of #145270 - jakubadamw:issue-144985, r=WaffleLapkin
Fix an ICE observed with an explicit tail-call in a default trait method

Right now, explicit tail-calls cannot be used in functions that hold the `#[track_caller]` attribute. This check is performed on a resolved concrete instance of a function, which would be absent for a tail-call performed from the body of a default trait method. This PR fixes the issue by checking for the relevant attribute in default trait methods separately, without expecting a specific resolved instance.

Closes https://github.com/rust-lang/rust/issues/144985.
2026-04-20 13:52:03 +02:00
Jonathan Brouwer
3ca43dc55e Rollup merge of #154654 - bushrat011899:core_io_error_kind, r=Mark-Simulacrum
Move `std::io::ErrorKind` to `core::io`

ACP: https://github.com/rust-lang/libs-team/issues/755
Tracking issue: https://github.com/rust-lang/rust/issues/154046
Related: https://github.com/rust-lang/rust/pull/152918

## Description

I consider rust-lang/rust#154046 to be really important for `no_std`, but I'm concerned rust-lang/rust#152918 might be too controversial. As an alternative, I'd like to propose starting small with `ErrorKind`, since it can be moved somewhat trivially. It has no dependencies on functionality in `std`, no platform specific behaviour, and could provide an excellent bridging point for `no_std` IO libraries.

Since `std::io::Error` implements `From<ErrorKind>`, libraries could write functions which return `Result<T, core::io::ErrorKind>`, and therefore be usable in `std`-using libraries with the `?` operator. For that reason, I'd consider this to be a worthwhile change even if the rest of `std::io` couldn't be moved to `core`/`alloc`, and entirely compatible with any efforts to make such a change in the future.

## Notes

* This is my first PR against Rust, please let me know if there's anything I should be doing that I have not done. I tried reading through the library contributors guide but I'm sure I've missed _something_.
* No AI tooling of any kind was used in the creation of this PR.
* I believe it's appropriate that this be a part of the linked tracking issue, but please let me know if that's not the case!
2026-04-20 13:52:03 +02:00
Oli Scherer
2892564a85 Merge visit_attribute 2026-04-20 13:34:08 +02:00
Oli Scherer
d67a570547 Merge visit_expr, visit_pat and visit_ty 2026-04-20 13:34:08 +02:00
Oli Scherer
f69d719e1c Merge visit_field_def 2026-04-20 13:34:08 +02:00
Oli Scherer
d2f476e57c Merge visit_variant 2026-04-20 13:34:08 +02:00
Oli Scherer
69aedb5ef2 Merge visit_crate 2026-04-20 13:33:48 +02:00
Oli Scherer
51d1e839d0 Merge visit_where_predicate 2026-04-20 13:33:48 +02:00
Oli Scherer
32ae2e5122 Merge visit_generic_param 2026-04-20 13:33:48 +02:00
Oli Scherer
05a49b6caa Merge some simple visitor functions 2026-04-20 13:33:48 +02:00
Oli Scherer
b1ec02fc12 Merge visit_assoc_item 2026-04-20 13:33:48 +02:00
Oli Scherer
3df953207d Merge visit_block 2026-04-20 13:33:48 +02:00
Oli Scherer
f98355e1ee Merge visit_stmt 2026-04-20 13:33:48 +02:00
Oli Scherer
a2cf11a976 Merge visit_foreign_item 2026-04-20 13:33:48 +02:00
Oli Scherer
90d0b41ef1 Merge visit_item 2026-04-20 13:33:48 +02:00
Oli Scherer
393f3e0110 Merge BuildReducedGraphVisitor initialization into DefPathVisitor 2026-04-20 13:33:24 +02:00
Oli Scherer
8a4f0dfb62 Rename DefCollector::resolver to r to match BuildReducedGraphVisitor::r 2026-04-20 13:32:54 +02:00
Laurențiu Nicola
dbaa5f18d5 Merge pull request #22110 from lnicola/sync-from-rust
minor: Sync from downstream
2026-04-20 11:30:10 +00:00
Laurențiu Nicola
4b8ef5c5f2 Fix formatting 2026-04-20 14:16:21 +03:00
Laurențiu Nicola
f08ee5b511 Merge ref 'e22c616e4e87' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@e22c616e4e
Filtered ref: rust-lang/rust-analyzer@37dc6b74ba
Upstream diff: e8e4541ff1...e22c616e4e

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-20 14:15:54 +03:00
Laurențiu Nicola
daab9fc647 Prepare for merging from rust-lang/rust
This updates the rust-version file to e22c616e4e.
2026-04-20 14:11:50 +03:00
Trevor Gross
90a0227843 support: Update vendored cfg-if to upstream for true and false support
Link: 15aec4a67e
2026-04-20 07:08:20 -04:00
Daria Sukhonina
93d0186957 Fix typo 2026-04-20 13:51:01 +03:00
Muhtasim-Rasheed
b1786813df Make E0284 generic argument suggestions more explicit 2026-04-20 16:46:57 +06:00
Vadim Petrochenkov
394c7172f4 resolve: Make sure visibilities of import declarations make sense
That they are all ordered inside the module and not more private than the module itself
The `import_decl_vis` logic is reused when reporting `ambiguous_import_visibilities` lint
Some asserts are hardened
Some relevant tests are added
2026-04-20 13:41:33 +03:00
Vadim Petrochenkov
38c14f301d resolve: Do not create unnecessary ParentScope when building external modules 2026-04-20 13:37:43 +03:00
Daria Sukhonina
72f25eea33 Replace ShardedHashMap method insert with debug-checked insert_unique 2026-04-20 13:22:22 +03:00
fru1tworld
e9856d7c15 Do not suggest removing param & when expr also has & 2026-04-20 18:42:24 +09:00
Jacob Adam
ac5734a779 Fix an ICE when using become in a default trait method
The logic determining whether the relevant function is marked as `#[track_caller]`
only worked with functions that could be resolved to a concrete instance, which default
trait methods cannot. We need to check the codegen attribute on the default method itself.

Co-authored-by: Folkert de Vries <folkert@folkertdev.nl>
2026-04-20 11:42:09 +02:00
bors
d12e1e12ae Auto merge of #155542 - JonathanBrouwer:rollup-F7GZlGr, r=JonathanBrouwer
Rollup of 10 pull requests

Successful merges:

 - rust-lang/rust#155054 (constify `Index(Mut)`, `Deref(Mut)` for `Vec`)
 - rust-lang/rust#155264 (Add autocast support for `x86amx`)
 - rust-lang/rust#155507 (suggest expect instead of unwrap when arg provided)
 - rust-lang/rust#154664 (core/num: Implement feature `integer_cast_extras`)
 - rust-lang/rust#155238 (compiletest: add a new diff for compare-out-by-lines tests.)
 - rust-lang/rust#155474 (Rename incremental `cfail`/`cpass` revisions to `bfail`/`bpass`)
 - rust-lang/rust#155493 (docs(num): fix stale link to `mem::Alignment`)
 - rust-lang/rust#155529 (Remove `AttributeLintKind` variants - part 3)
 - rust-lang/rust#155531 (Tweak `is_ascii_punctuation()` docs wording)
 - rust-lang/rust#155533 (Provide a const new for `GlobalCache`)
2026-04-20 09:29:42 +00:00
Nicholas Nethercote
5e00b8e7d5 Remove some unnecessary lifetimes.
We have a number of structs with more lifetimes than necessary. This
commit removes them.

LLM disclosure: I asked Claude Code to check for unnecessary lifetimes
in all types with three or more lifetimes, and it produced a list of
candidates (half of which were invalid). I did the modifications for the
valid cases myself, and found a couple more cases along the way.
2026-04-20 19:25:51 +10:00
Zac Harrold
fe2b39f064 Move std::io::ErrorKind to core::io
Move `std::io::ErrorKind` to `core::io`
* Update `rustdoc-html` tests for the new path
* Add `core_io` feature to control stability. This replaces the use of `core_io_borrowed_buf` on the `core::io` module itself.
* Re-export `core::io::ErrorKind` in `std::io::error`
2026-04-20 18:38:25 +10:00
Usman Akinyemi
8b6f7fbd8d Improve E0308 error message for impl Trait return mismatches
When a function returns `impl Trait`, all branches must return the same
concrete type. Previously, the compiler showed:

    expected `First` because of return type

This was misleading, as it suggested the return type was `First`, rather
than any single type implementing the trait.

Update the diagnostic to:

    expected a single type implementing `Value` because of return type

Also highlight the first return expression to make it clearer why
subsequent returns do not match.

Signed-off-by: Usman Akinyemi <usmanakinyemi202@gmail.com>
2026-04-20 13:59:39 +05:30
Jynn Nelson
38debc3949 bootstrap: Make "detected modifications" for download-rustc less verbose 2026-04-20 10:00:13 +02:00
Ralf Jung
ecd63169d8 Merge pull request #4970 from rust-lang/rustup-2026-04-20
Automatic Rustup
2026-04-20 06:59:56 +00:00
Shoyu Vanilla (Flint)
3398413631 Merge pull request #22054 from jdrouet/jdrouet/remove-duplicate-lints
fix(21943): remove duplicate lints
2026-04-20 06:56:44 +00:00
Jeremie Drouet
6c13e42a1d fix: filter rules by names before pushing them
Signed-off-by: Jeremie Drouet <jeremie.drouet@gmail.com>
2026-04-20 08:47:37 +02:00
Jonathan Brouwer
d00c0476e7 Rollup merge of #155533 - ChayimFriedman2:const-cache-new, r=ShoyuVanilla
Provide a const new for `GlobalCache`

This can help rust-analyzer a bit.
2026-04-20 08:14:15 +02:00
Jonathan Brouwer
2e5a9fc307 Rollup merge of #155531 - Jules-Bertholet:is_ascii_punctuation_docs, r=scottmcm
Tweak `is_ascii_punctuation()` docs wording

These methods return `true` for characters with Unicode general category of punctuation (P), but also for those with general category of symbol (S).

@rustbot label A-docs
2026-04-20 08:14:14 +02:00
Jonathan Brouwer
055543f263 Rollup merge of #155529 - GuillaumeGomez:rm-attributelintkind, r=JonathanBrouwer
Remove `AttributeLintKind` variants - part 3

Part of https://github.com/rust-lang/rust/issues/153099.

r? @JonathanBrouwer
2026-04-20 08:14:14 +02:00
Jonathan Brouwer
ede69dad7d Rollup merge of #155493 - sorairolake:fix-alignment-doc-link, r=scottmcm
docs(num): fix stale link to `mem::Alignment`

This pull request updates a stale link to `mem::Alignment` in `num::IntErrorKind`.

In rust-lang/rust#153178, I added a link to `Alignment` in `IntErrorKind`, but I overlooked that `Alignment` had been moved from `core::ptr` to `core::mem`. Although it is still re-exported in `core::ptr`, this pull request points the link to its canonical location.

@rustbot label +A-docs
2026-04-20 08:14:13 +02:00
Jonathan Brouwer
fda59bfb6f Rollup merge of #155474 - Zalathar:bpass, r=jieyouxu
Rename incremental `cfail`/`cpass` revisions to `bfail`/`bpass`

Long ago, UI tests were divided into *compile* and *run* tests. Later, the compile tests were further subdivided into *check* and *build* tests, to speed up tests that don't need a full build.

The same split was never applied to incremental test revisions, so the only way to perform a check build in incremental tests is (confusingly) to use a `cfail` revision and then specify `//@ check-fail` or `//@ check-pass`.

This PR makes room for dedicated check-fail and check-pass revisions by renaming the existing `cfail` and `cpass` revisions to `bfail` and `bpass`, since they currently perform a full build.

---

The test updates were done with a regex whole-word find-and-replace for `c(fail|pass)(\d*)`, and I also took the opportunity to manually add a space after `revisions:` on affected lines.

r? jieyouxu
2026-04-20 08:14:12 +02:00
Jonathan Brouwer
1204fb1445 Rollup merge of #155238 - Ozzy1423:diff-by-lines, r=jieyouxu
compiletest: add a new diff for compare-out-by-lines tests.

Previously, when comparing output by lines, only the actual diff was shown. This is unhelpful since we expect lines to be shuffled around.

With this new print, we can see the exact lines that are missing or have appeared without the noise of the moved around lines.

Example, in this case a note has moved slightly so there is one more separator line "|":

```
+	   |
+	   = help: maybe it is overwritten before being read?

Compare output by lines enabled, diff by lines:
Expected contains these lines that are not in actual:
(no lines found)
Actual contains these lines that are not in expected:
   |

The actual stderr differed from the expected stderr
To update references, rerun the tests and pass the `--bless` flag
To only update this specific test, also pass `--test-args liveness/liveness-consts.rs`
```

r? @jieyouxu
cc @zetanumbers @ywxt
2026-04-20 08:14:12 +02:00
Jonathan Brouwer
26f47ae831 Rollup merge of #154664 - okaneco:integer_cast_extras, r=scottmcm
core/num: Implement feature `integer_cast_extras`

Tracking issue https://github.com/rust-lang/rust/issues/154650
Accepted ACP https://github.com/rust-lang/libs-team/issues/765#issuecomment-4164285847

Implement `saturating`, `checked`, and `strict` casting between signed and unsigned integer primitives of the same bit-width.

Add `cast_integer` panic function to `overflow_panic.rs`
2026-04-20 08:14:11 +02:00
Jonathan Brouwer
8beed17a3d Rollup merge of #155507 - Kivooeo:no-expect, r=mejrs
suggest expect instead of unwrap when arg provided

r? mejrs (feel free to reroll)

fixes https://github.com/rust-lang/rust/issues/155502
2026-04-20 08:14:10 +02:00
Jonathan Brouwer
cccf996225 Rollup merge of #155264 - sayantn:amx-autocast, r=dianqk
Add autocast support for `x86amx`

Builds on rust-lang/rust#140763 by further adding autocasts for `x86amx` from/to vectors of size 8192 bits.

This also disables SIMD vector abi checks for the `"unadjusted"` abi because
 - This is primarily used to link with LLVM intrinsics, which don't actually lower to function calls with vector arguments. Even with other cg backends, this is true.
 - This ABI is internal and perma-unstable (and also super specific), so it is very unlikely that this will cause breakages.
 - (The primary reason) Without doing this we can't actually use 8192 bit long vectors to represent `x86amx`

> Why do we need a bypass for `x86amx`? Can't we use a `#[lang_item]` or something?

If `x86amx` was a normal LLVM type, this approach would've worked and I would also prefer it. But LLVM specifies that

> No instruction is allowed for this type. There are no arguments, arrays, pointers, vectors or constants of this type.

So we can't treat it like a normal type at all -- even if we add it like a lang-item, we would still have to special-case everywhere to check if we are passing to the correct LLVM intrinsic, and only then use the `x86amx` type. IMO this is needlessly complex, and way worse than this solution, which just adds it to the autocast list in cg_llvm

r? codegen
2026-04-20 08:14:10 +02:00
Jonathan Brouwer
ce91732a75 Rollup merge of #155054 - Lars-Schumann:const-vec-ops, r=dtolnay
constify `Index(Mut)`, `Deref(Mut)` for `Vec`

Relevant tracking issues
const_convert: https://github.com/rust-lang/rust/issues/143773
const_index: https://github.com/rust-lang/rust/issues/143775
2026-04-20 08:14:09 +02:00
Chayim Refael Friedman
592c8154de Add #[rust_analyzer::prefer_underscore_import] to the traits in rustc_type_ir::inherent
This is a new attribute that instructs rust-analyzer to prefer importing the trait `as _`. It is useful for these traits
since their names often clashes with the type.
2026-04-20 09:04:01 +03:00
The Miri Cronjob Bot
d5ebbc472a fmt 2026-04-20 05:53:05 +00:00
The Miri Cronjob Bot
366676bd9d Merge ref 'e22c616e4e87' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@e22c616e4e
Filtered ref: rust-lang/miri@1aa2d78abd
Upstream diff: 6f109d8a2d...e22c616e4e

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-20 05:52:31 +00:00
The Miri Cronjob Bot
08e9e1775c Prepare for merging from rust-lang/rust
This updates the rust-version file to e22c616e4e.
2026-04-20 05:44:36 +00:00
Tshepang Mbambo
f52759503e Merge pull request #2840 from rust-lang/rustc-pull
Rustc pull update
2026-04-20 07:37:17 +02:00
cijiugechu
f6294883f8 Make reparsed guard metavars collect tokens 2026-04-20 13:36:27 +08:00
Oscar Bray
459be3e7b1 compiletest: add a new diff for compare-out-by-lines tests.
Previously, when comparing output by lines, only the actual
diff was shown. This is unhelpful since we expect lines to be
shuffled around.

With this new print, we can see the exact lines that are missing
or have appeared without the noise of the moved around lines.
2026-04-20 06:31:21 +01:00
The rustc-josh-sync Cronjob Bot
3b694e5a6b Merge ref 'e22c616e4e87' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@e22c616e4e
Filtered ref: rust-lang/rustc-dev-guide@592b9fba6c
Upstream diff: 17584a1819...e22c616e4e

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-20 05:21:01 +00:00
The rustc-josh-sync Cronjob Bot
f6f98eb65f Prepare for merging from rust-lang/rust
This updates the rust-version file to e22c616e4e.
2026-04-20 05:14:21 +00:00
Chayim Refael Friedman
ac905cc4cd Fix forgotten case in walk_child_exprs() 2026-04-20 06:31:38 +03:00
Shoyu Vanilla (Flint)
b503f3848d Merge pull request #22105 from Shourya742/2026-04-20-replace-most-make-with-editor-specific-make
Replace make with SyntaxFactory in few handlers
2026-04-20 03:25:09 +00:00
bit-aloo
828238538b migrate wrap_unwrap_cfg_attr to SyntaxEditor 2026-04-20 08:42:56 +05:30
bit-aloo
807a0396db Replace make with SyntaxFactory in unwrap_block 2026-04-20 08:41:45 +05:30
bit-aloo
583b5f4564 Replace make with SyntaxFactory in unmerge_imports 2026-04-20 08:41:17 +05:30
bit-aloo
c4b90238d2 Replace make with SyntaxFactory in remove_dbg 2026-04-20 08:40:45 +05:30
bit-aloo
82e654a6b7 Replace make with SyntaxFactory in generate_trait_from_impl.rs 2026-04-20 08:38:39 +05:30
bit-aloo
8e8d71947f Replace make with SyntaxFactory in convert_tuple_struct_to_named_struct 2026-04-20 08:38:14 +05:30
bit-aloo
27c4d58747 Replace make with SyntaxFactory in convert_named_struct_to_tuple_struct 2026-04-20 08:37:35 +05:30
bit-aloo
a5fb3511f7 Replace make with SyntaxFactory in add_missing_match_arms 2026-04-20 08:37:06 +05:30
Chayim Refael Friedman
a49a2b5370 Merge pull request #22104 from ChayimFriedman2/reinit-cache
perf: Do not check solver's cache validity on every access
2026-04-20 02:46:42 +00:00
Chayim Refael Friedman
5657220319 Do not check solver's cache validity on every access
This should help speed.

Instead, we do it only when an `Interner` is constructed, since an interner cannot be held across revisions.

There is a problem, though: an interner *can* be held across different databases. To solve that, we also reinit the cache when attaching databases, and take the assumption that everything significant (i.e. that can access the cache) will need to attach the db. This is somewhat risky, but we'll take it for the speed.

Theoretically we could *only* reinit on db attach, but it's less risky this way, and with-crate interner construction is rare.
2026-04-20 05:36:49 +03:00
Jules Bertholet
fd65209a77 Tweak is_ascii_punctuation()/graphic() docs wording
The `_punctuation` methods return `true` for characters with
Unicode general category of punctuation (P),
but also for those with general category
of symbol (S).
2026-04-19 22:27:16 -04:00
Chayim Refael Friedman
5749fe87e9 Provide a const new for GlobalCache
This can help rust-analyzer a bit.
2026-04-20 04:52:59 +03:00
🍌Shawn
e1059f6e53 Fix redundant boolean comparison in Mutex::try_lock 2026-04-20 09:49:52 +08:00
Chayim Refael Friedman
3fedae8b75 Accept an ExpressionStoreOwnerId for pretty-printing
And not a DefWithBodyId.
2026-04-20 03:40:04 +03:00
Chayim Refael Friedman
76271a7c84 In async closures, make the returned async blocks the bindings owner of the bindings inside
Previously it was the closure, which is incorrect.
2026-04-20 03:40:04 +03:00
Chayim Refael Friedman
5ec1a727be Add missing interner lang items 2026-04-20 03:40:04 +03:00
Guillaume Gomez
6d23cf97da Remove AttributeLintKind::DocUnknownInclude variant 2026-04-20 02:23:56 +02:00
Nicholas Nethercote
e192eec395 Remove duplicated Flags methods.
The `Flags` trait has two methods: `flags` and `outer_exclusive_binder`.
Multiple types impl this trait and then also have duplicate inherent
methods with the same names; these are all marked with "Think about
removing this" comments. This is left over from things being moved into
`rustc_type_ir`.

This commit removes those inherent methods. This requires adding `use
Flags` to a number of files.
2026-04-20 10:13:53 +10:00
Guillaume Gomez
4b2e2ace23 Remove unused AttributeLintKind::DocInvalid variant 2026-04-20 02:09:33 +02:00
Guillaume Gomez
dacc42fb1b Remove AttributeLintKind::DocAutoCfgHideShowExpectsList variant 2026-04-20 02:08:18 +02:00
Guillaume Gomez
d7d9cf9153 Remove AttributeLintKind::DocAutoCfgHideShowUnexpectedItem variant 2026-04-20 01:59:03 +02:00
Guillaume Gomez
ace320fba3 Remove AttributeLintKind::AmbiguousDeriveHelpers variant 2026-04-20 00:50:55 +02:00
Zac Harrold
6960e7c958 Adjust usage of std::io::ErrorKind to be core compatible
* Checking exhaustion will no longer be possible for `repr_bitpacked`. Moving `kind_from_prim` into an associated function, and setting it up to be moved into `core::io` as well.
* `ErrorKind::as_str` is private, but it's only usage is trivially replaced with `Display::fmt`
* The features io_error_inprogress, io_error_more, and io_error_uncategorized will all need to be enabled
2026-04-20 08:29:15 +10:00
Zac Harrold
08bd077df4 Make documentation for std::io::ErrorKind core::io compatible
Certain links will not be valid when moved into `core::io`
2026-04-20 08:29:15 +10:00
Chayim Refael Friedman
333cd70b88 Merge pull request #22099 from BenjaminBrienen/fix-header
fix lsp-extensions section header
2026-04-19 22:04:18 +00:00
Mads Marquart
3695fefd93 Add a test for Mach-O link_section API inherited from LLVM 2026-04-19 23:49:02 +02:00
BenjaminBrienen
de9958bcad fix lsp-extensions section header 2026-04-19 23:29:54 +02:00
Chayim Refael Friedman
91f77846b9 Merge pull request #22096 from ShoyuVanilla/issue-21885
fix: Use `ProofTreeVisitor` for unsized coercion
2026-04-19 19:39:58 +00:00
Shoyu Vanilla (Flint)
5247dd6dbc Merge pull request #22087 from A4-Tacks/self-ty-hints
fix: Fix incorrect lifetime hints for self with type
2026-04-19 19:20:10 +00:00
bors
e22c616e4e Auto merge of #155083 - adwinwhite:introduce-unnormalized, r=lcnr
Introduce `Unnormalized` wrapper




This is the first step of the [eager normalization](https://rust-lang.zulipchat.com/#narrow/channel/364551-t-types.2Ftrait-system-refactor/topic/Eager.20normalization.2C.20ahoy.21/with/582996293) series.

This PR introduce an `Unnormalized` wrapper and make most normalization routines consume it. The purpose is to make normalization explicit. 
This PR contains no behavior change.

API changes are in the first two commit. 
There're some normalization routines left untouched:
- `normalize` in the type checker of borrowck: better do it together with `field.ty()` returning `Unnormalized`.
- `normalize_with_depth`: only used inside the old solver. Can be done later.
- `query_normalize`: rarely used.
- misc local normalization helpers.

The compiler errors are mostly fixed via `ast-grep`, with exceptions handled manually.
2026-04-19 19:18:17 +00:00
Shoyu Vanilla (Flint)
b603664e89 Merge pull request #22095 from Shourya742/2026-04-19-replace-make-with-Syntax-factory-convert-range-for-to-while
Replace make with SyntaxFactory in convert reange for to while
2026-04-19 19:12:02 +00:00
Shoyu Vanilla
f946c4d17e fix: Use ProofTreeVisitor for unsized coercion 2026-04-20 04:05:31 +09:00
Mahdi Ali-Raihan
c567332927 Implemented PermissionsExt ACP on Windows, which provides functions/utilities to observe, set, and create a Permissions struct with certain file attributes 2026-04-19 14:46:48 -04:00
sharesth23
ee82742dfb Fix LLVM offload install docs to use semicolon-separated CMake lists
Update  so the LLVM
CMake example uses  and , which is the
correct list separator syntax for LLVM CMake options.[Docs] Remove shortcode from models page heading
2026-04-20 00:01:17 +05:30
bit-aloo
b45a460539 remove make from convert reange for to while 2026-04-19 22:48:24 +05:30
Folkert de Vries
640c4b4f1e cmse: test returning MaybeUninit<T>
The `MaybeUninit` type is `repr(transparent)`, so returning a `MaybeUninit<u64>` should work. The same is not true when using C or rust union types.
2026-04-19 18:34:14 +02:00
Folkert de Vries
aa38b7fcac add MaybeUninit to minicore 2026-04-19 18:27:10 +02:00
Adwin White
6279106e72 fix all errors 2026-04-20 00:18:28 +08:00
Adwin White
3e1e35b5d1 make common normalization routines take Unnormalized 2026-04-20 00:08:14 +08:00
Adwin White
5c12b9283e introduce Unnormalized wrapper and make instantiation use it 2026-04-20 00:08:14 +08:00
bors
38799a320d Auto merge of #155519 - JonathanBrouwer:rollup-P17uwTS, r=JonathanBrouwer
Rollup of 12 pull requests

Successful merges:

 - rust-lang/rust#155370 (Add regression test for dead code elimination with drop + panic)
 - rust-lang/rust#154823 (Replace the spdx-rs dependency with a minimal in-tree SPDX tag-value parser)
 - rust-lang/rust#155294 (Add test for coalescing of diagnostic attribute duplicates)
 - rust-lang/rust#155352 (triagebot.toml: Sync `assign.owners` with `autolabel."T-compiler"`)
 - rust-lang/rust#155431 (Add temporary scope to assert_matches)
 - rust-lang/rust#153873 (deprecate `std::char` constants and functions)
 - rust-lang/rust#154865 (libtest: use binary search for --exact test filtering)
 - rust-lang/rust#154979 (add #[must_use] macros for floats)
 - rust-lang/rust#155486 (c-variadic: add roundtrip test)
 - rust-lang/rust#155504 (Remove `AttributeLintKind` variants - part 2)
 - rust-lang/rust#155510 (Update Tidy python executable path)
 - rust-lang/rust#155514 (codegen-options docs: remove -Csoft-float)
2026-04-19 16:04:18 +00:00
Shoyu Vanilla (Flint)
4c365a349a Merge pull request #22092 from ShoyuVanilla/fudge
Sync function call args check fudging with rustc
2026-04-19 14:12:06 +00:00
Jonathan Brouwer
cd8752bc30 Rollup merge of #155514 - RalfJung:softfloat-docs, r=JonathanBrouwer
codegen-options docs: remove -Csoft-float

This got removed in rust-lang/rust#154106 but I didn't realize there are still docs mentioning it.
2026-04-19 16:04:35 +02:00
Jonathan Brouwer
772e85662e Rollup merge of #155510 - Walnut356:python_path, r=jieyouxu
Update Tidy python executable path

Resolves https://github.com/rust-lang/rust/issues/155480

r? @Kobzol
2026-04-19 16:04:35 +02:00
Jonathan Brouwer
5503f576bf Rollup merge of #155504 - GuillaumeGomez:rm-attributelintkind, r=JonathanBrouwer
Remove `AttributeLintKind` variants - part 2

Follow-up of https://github.com/rust-lang/rust/pull/154432.
Part of https://github.com/rust-lang/rust/issues/153099.

r? @JonathanBrouwer
2026-04-19 16:04:34 +02:00
Jonathan Brouwer
0f6fe2ea22 Rollup merge of #155486 - folkertdev:c-variadic-roundtrip, r=RalfJung
c-variadic: add roundtrip test

tracking issue: https://github.com/rust-lang/rust/issues/44930

Test that our `va_arg` implementation matches (as in, can decode) how LLVM passes c-variadic arguments.

And some comment followup to https://github.com/rust-lang/rust/pull/152980 (cc @RalfJung, feel free to review this PR too btw).

r? tgross35
2026-04-19 16:04:34 +02:00
Jonathan Brouwer
e7c135e282 Rollup merge of #154979 - ArtemIsmagilov:must-use-floats, r=jhpratt
add #[must_use] macros for floats

try resolve rust-lang/rust#154854
2026-04-19 16:04:33 +02:00
Jonathan Brouwer
7b658037fd Rollup merge of #154865 - sunshowers:binary-search-test, r=Mark-Simulacrum
libtest: use binary search for --exact test filtering

When `--exact` is passed in, use binary search for O(f log n) lookups instead of an O(n) linear scan, under the assumption that f << n (which is true for the most relevant cases).

This is important for Miri, where the interpreted execution makes the linear scan very expensive.

I measured this against a repo with 1000 empty tests, running `cargo +stage1 miri nextest run test_00` (100 tests) under hyperfine:

* Before (linear scan): 49.7s ± 0.6s
* After (binary search): 41.9s ± 0.2s  (-15.7%)

I also tried a few other variations (particularly swapping matching tests to the front of the list + truncating the list), but the index + swap_remove approach proved to be the fastest.

Questions:

- [ ] To be conservative, I've assumed that test_main can potentially receive an unsorted list of tests. Is this assumption correct?
2026-04-19 16:04:32 +02:00
Jonathan Brouwer
b07688dc2e Rollup merge of #153873 - folkertdev:deprecate-char-max, r=Mark-Simulacrum
deprecate `std::char` constants and functions

similar to how constants in those modules for numeric types have been deprecated. The `std::char` module contains:

Three stable constants that this PR deprecates. These already link to their associated constant equivalents.

- `MAX`
- `REPLACEMENT_CHARACTER`
- `UNICODE_VERSION`

two unstable constants that this PR removes. The constants are already stablized as associated constants on `char`.

- `MAX_LEN_UTF8`
- `MAX_LEN_UTF16`

Four stable functions that this PR deprecates. These already link to their method equivalents.

- `fn decode_utf16`
- `fn from_digit`
- `fn from_u32`
- `fn from_u32_unchecked⚠`

discussion at [#t-libs > should &#96;std::char::{MIN, MAX}&#96; be deprecated?](https://rust-lang.zulipchat.com/#narrow/channel/219381-t-libs/topic/should.20.60std.3A.3Achar.3A.3A.7BMIN.2C.20MAX.7D.60.20be.20deprecated.3F/with/579444750).

r? libs-api
2026-04-19 16:04:32 +02:00
Jonathan Brouwer
ffcda118ca Rollup merge of #155431 - Voultapher:add-tmp-scope-to-assert-matches, r=Amanieu
Add temporary scope to assert_matches

Addresses https://github.com/rust-lang/rust/issues/154406 in part. `assert_eq` will be done in a separate PR.
2026-04-19 16:04:31 +02:00
Jonathan Brouwer
f86378ca17 Rollup merge of #155352 - Enselic:label-sync, r=Mark-Simulacrum
triagebot.toml: Sync `assign.owners` with `autolabel."T-compiler"`

In `autolabel."T-compiler"`, several `./tests/*` dirs are listed.

But many of them are missing from `assign.owners`. Add them all to `assign.owners` so reviewers are picked from the compiler group, and not from the small `assign.adhoc_groups.fallback` group.

Discovered in https://github.com/rust-lang/rust/pull/153941#issuecomment-4065145752.

CC fallback group @Mark-Simulacrum @jieyouxu who can maybe confirm that the old setup was not intentional? (Edit: I hope it was not intentional, because in that case I should have reached out to you personally beforehand.)
2026-04-19 16:04:30 +02:00
Jonathan Brouwer
fa8db59673 Rollup merge of #155294 - mejrs:coalescing, r=chenyukang
Add test for coalescing of diagnostic attribute duplicates

There is an existing [test](github.com/rust-lang/rust/blob/main/tests/ui/diagnostic_namespace/on_unimplemented/report_warning_on_duplicated_options.rs) that warnings for duplicates are emitted, but not for the messages themselves.
2026-04-19 16:04:30 +02:00
Jonathan Brouwer
0883b8cc79 Rollup merge of #154823 - jakubadamw:spdx-rs-replacement, r=Mark-Simulacrum
Replace the spdx-rs dependency with a minimal in-tree SPDX tag-value parser

The spdx-rs crate [is no longer maintained](https://github.com/doubleopen-project/spdx-rs/pulls) and is behind on its own dependency updates. It is currently used in [the collect-license-metadata tool](https://github.com/rust-lang/rust/tree/main/src/tools/collect-license-metadata), employing a single function therefrom: `spdx_rs::parsers::spdx_from_tag_value`, which parses the output of the `reuse` tool to extract file names, licences and copyright text.

This PR replaces the use of said function with a small minimal parser that handles just the subset of the SPDX tag-value format that is needed: `Tag: Value` line pairs and multi-line `<text>...</text>` blocks.

Coincidentally, this gets rid of the last transitive dependency on syn v1.
2026-04-19 16:04:29 +02:00
Jonathan Brouwer
8beec0111d Rollup merge of #155370 - iyernaveenr:naveen_r_iyer/issue-114532-needs-test, r=Mark-Simulacrum
Add regression test for dead code elimination with drop + panic

Add a codegen test for rust-lang/rust#114532.

The bug was that dead code elimination failed when a `Drop` impl contained a `panic!` and a potentially-panicking external function was called after the value was created. This was fixed since 1.82 but no regression test was added.

The test verifies that `foo()` compiles to just a call to `unknown()` + `ret void`, with no panic or panicking call in the function body.

Closes rust-lang/rust#114532
2026-04-19 16:04:29 +02:00
Shoyu Vanilla (Flint)
1d9e4ebeda Merge pull request #22093 from ShoyuVanilla/bump-scip
minor: Bump `scip`
2026-04-19 13:28:59 +00:00
Chayim Refael Friedman
298aea12c7 Merge pull request #21740 from ChayimFriedman2/prefer-underscore-import
feat: Allow crate authors to declare that their trait prefers to be imported `as _`
2026-04-19 13:28:27 +00:00
Shoyu Vanilla
b1563cdd02 minor: Bump scip 2026-04-19 22:19:01 +09:00
Shoyu Vanilla (Flint)
07120929cb Merge pull request #22091 from Shourya742/2026-04-19-remove-generate-impl-text
Remove generate impl text from utils
2026-04-19 13:09:00 +00:00
bors
22cc6747b1 Auto merge of #155444 - bjorn3:update_deps, r=jieyouxu
Update a bunch of dependencies to reduce windows-sys duplication

This gets rid of windows-sys 0.60 and with the exception of curl and stacker it gets rid of windows-sys 0.59. For stacker getting rid of windows-sys 0.59 is blocked on https://github.com/rust-lang/stacker/pull/145 and https://github.com/rust-lang/rust/pull/155438.
2026-04-19 12:46:26 +00:00
Shoyu Vanilla (Flint)
200c6992cc Merge pull request #22081 from A4-Tacks/migrate-loop-iter-for
internal: Migrate `convert_iter_for_each_to_for` assist to SyntaxEditor
2026-04-19 12:22:58 +00:00
Shoyu Vanilla
d9046fe9f4 Sync function call args check fudging with rustc 2026-04-19 21:18:23 +09:00
bit-aloo
9ead6cedd3 remove unused methods in utils 2026-04-19 17:16:18 +05:30
bit-aloo
3b6cc1d4a8 migrate generate_enum_projection_method to syntax editor 2026-04-19 17:15:46 +05:30
bit-aloo
c31e75dae0 migrate generate_enum_is_method to syntax editor 2026-04-19 17:15:02 +05:30
Ralf Jung
02a8982069 codegen-options docs: remove -Csoft-float 2026-04-19 13:32:40 +02:00
Ralf Jung
bf61e56551 Merge pull request #4969 from rust-lang/rustup-2026-04-19
Automatic Rustup
2026-04-19 10:59:56 +00:00
Folkert de Vries
fa740c7255 refactor llvm va_arg intrinsic validation logic 2026-04-19 12:54:43 +02:00
Folkert de Vries
a852582b35 test that c-variadic arguments roundtrip 2026-04-19 12:51:03 +02:00
Ralf Jung
8aefb076b9 clippy 2026-04-19 12:35:25 +02:00
Ohad Ravid
846974e1b0 Don't count storage statements in size_estimate query 2026-04-19 11:05:17 +03:00
CoCo-Japan-pan
0e6efe57d7 Update UI tests 2026-04-19 16:38:04 +09:00
Walnut
e13412f2c0 update python executable path 2026-04-19 02:31:47 -05:00
CoCo-Japan-pan
614994fb8b Update HIR pretty printing 2026-04-19 15:58:02 +09:00
CoCo-Japan-pan
a0b8e89456 Update AST pretty printing 2026-04-19 15:58:02 +09:00
CoCo-Japan-pan
5d8a2977b1 Update rustfmt 2026-04-19 15:58:02 +09:00
CoCo-Japan-pan
56211738ea Reorder keywords to place restrictions next to visibility 2026-04-19 15:57:54 +09:00
Chayim Refael Friedman
31f4abbe3c Merge pull request #22086 from rust-lang/ci/gen-lints
Update generated lints
2026-04-19 06:23:50 +00:00
The Miri Cronjob Bot
ed395bba8d Merge ref '6f109d8a2da2' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@6f109d8a2d
Filtered ref: rust-lang/miri@b3bc25a96b
Upstream diff: 4c4205163a...6f109d8a2d

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-19 05:48:19 +00:00
The Miri Cronjob Bot
2bdf36189d Prepare for merging from rust-lang/rust
This updates the rust-version file to 6f109d8a2d.
2026-04-19 05:40:08 +00:00
Laurențiu Nicola
a0b8651d9d Merge pull request #22034 from rust-lang/dependabot/cargo/rand-0.9.3
build(deps): bump rand from 0.9.2 to 0.9.3
2026-04-19 05:22:26 +00:00
Laurențiu Nicola
84d3cbec4e Merge pull request #22053 from rust-lang/dependabot/npm_and_yarn/editors/code/follow-redirects-1.16.0
Bump follow-redirects from 1.15.9 to 1.16.0 in /editors/code
2026-04-19 05:20:48 +00:00
Laurențiu Nicola
d336d728ac Merge pull request #22056 from rust-lang/dependabot/cargo/thin-vec-0.2.16
Bump thin-vec from 0.2.14 to 0.2.16
2026-04-19 05:19:54 +00:00
Laurențiu Nicola
a57f175b15 Merge pull request #22060 from rust-lang/rustc-pull
Rustc pull update
2026-04-19 05:18:07 +00:00
yukang
eedf870de9 Suggest returning a reference for unsized place from a closure 2026-04-19 13:15:41 +08:00
Chayim Refael Friedman
e332799541 Merge pull request #22061 from Veykril/veykril/push-zyolmvzxtoqz
Bump salsa
2026-04-19 04:52:14 +00:00
yukang
ae05a49f33 Fix wrong suggestion for returning async closure 2026-04-19 12:32:26 +08:00
Kivooeo
e4c852dece add suggestion for expect 2026-04-19 15:04:06 +11:00
bors
ec2d669db8 Auto merge of #155470 - weihanglo:update-cargo, r=weihanglo
Update cargo submodule

28 commits in eb94155a9a60943bd7b1cb04abec42f5d0de6ddc..7ecf0285ebb408d596e4a8ac76a0980d8edb7005
2026-04-09 13:10:20 +0000 to 2026-04-18 15:34:11 +0000
- fix: use `portable-atomic` for 64-bit atomics (rust-lang/cargo#16906)
- fix: rename incorrectly documented target-spec-json to json-target-sp… (rust-lang/cargo#16905)
- Add global HTTP timeout tracking to http_async (rust-lang/cargo#16903)
- feat(config): Stabilize `resolver.lockfile-path` config (rust-lang/cargo#16694)
- chore(deps): update msrv (1 version) to v1.95 (rust-lang/cargo#16897)
- fix: rebuild rustdoc json for different versions of a same crate (rust-lang/cargo#16773)
- Add effective_url to http_async (rust-lang/cargo#16899)
- Make crate downloads process as a queue rather than a stack (rust-lang/cargo#16898)
- fix: sparse registry fetch progress reporting (rust-lang/cargo#16900)
- chore: bump to 0.98.0; update changelog (rust-lang/cargo#16892)
- docs(semver-check): update diagnostics to Rust 1.95 (rust-lang/cargo#16895)
- docs(ref): Better highlight 'package --list' for include/exclude (rust-lang/cargo#16891)
- docs: `include` doesnt apply gitignore from repo (rust-lang/cargo#16890)
- fix: Update `bash` and `zsh` Autocompletion Documents to add `-m` (rust-lang/cargo#16888)
- Add `-m` shorthand for `--manifest-path` (rust-lang/cargo#16858)
- Fix a typo (rust-lang/cargo#16885)
- Always take a shared lock on `.cargo-lock` (rust-lang/cargo#16886)
- fix(toml): Teach users how to pin edition (rust-lang/cargo#16851)
- fix: Prefer defined lint levels over default (rust-lang/cargo#16879)
- chore(deps): bump rand from 0.10.0 to 0.10.1 (rust-lang/cargo#16883)
- fix(lints): Ignore unused_crate_dependencies status (rust-lang/cargo#16877)
- Copy cargo clean target-dir validation tests to clean_new_layout.rs (rust-lang/cargo#16878)
- cargo clean: Add target directory validation (rust-lang/cargo#16712)
- Docs: "api" in the configuration should not include a trailing slash (rust-lang/cargo#16869)
- fix(core): use `closest_msg` to suggest similar member name for mistyped `-p` (rust-lang/cargo#16844)
- chore(ci): Pin GitHub Actions to commit SHAs (rust-lang/cargo#16868)
- chore(ci): Update `actions/checkout` from v5 to v6 (rust-lang/cargo#16867)
- Add test for cargo install with github fastpath (rust-lang/cargo#16866)
2026-04-19 03:53:57 +00:00
Trevor Gross
996b57d5bc test: Fix printing bitwise float reprs in error printing
In commit "test: Consolidate `Hexf`, `Hexi`, and the `Hex` trait" we
unintentionally lost the difference between float hex and bitwise hex
formatting; instead, the float hex was getting printed twice. Resolve
this by printing the integer hex whenever the `-` format modifier is
specified.  This also makes things simpler because we no longer need to
keep track of whether an `impl DisplayHex` is a float with `.to_bits()`
available or an integer without it, we can always just try to print both
forms.

As a result, we can use a common error message for all validation
checks.
2026-04-18 23:51:56 -04:00
A4-Tacks
3eb5a1bd85 Rename param edit to editor for add_file_edits 2026-04-19 11:05:25 +08:00
A4-Tacks
baad04a0ae internal: Migrate convert_iter_for_each_to_for assist to SyntaxEditor 2026-04-19 11:02:21 +08:00
A4-Tacks
a207636bbe fix: Fix incorrect lifetime hints for self with type
Example
---
**Before this PR**

```rust
fn foo(self: &Self, a: &()) -> &() {}
// ^^^<'0, '1>
          // ^'0       ^'1     ^'1
```

**After this PR**

```rust
fn foo(self: &Self, a: &()) -> &() {}
// ^^^<'0, '1>
          // ^'0       ^'1     ^'0
```
2026-04-19 10:58:10 +08:00
Chayim Refael Friedman
79963ace70 Allow crate authors to declare that their trait prefers to be imported as _
For example for extension traits.

Provide an attribute for that. It'll affect flyimport and the autoimport quickfix, as explained in the code.
2026-04-19 05:52:30 +03:00
Chayim Refael Friedman
599a7e1632 Merge pull request #22070 from A4-Tacks/extract-ty-alias-name
fix: adjust name of extract_type_alias
2026-04-19 02:48:54 +00:00
Chayim Refael Friedman
5c09a5537d Merge pull request #22083 from ada4a/22062-deprecatedness
fix: respect `#[deprecated]` attr when deciding if a `ModuleDef` completion is `deprecated`
2026-04-19 02:42:04 +00:00
Chayim Refael Friedman
4ac95f5cd2 Merge pull request #21906 from Young-Flash/master
feat: exclude refs(find all refs) from deps and stdlib
2026-04-19 02:29:28 +00:00
Chayim Refael Friedman
12094bd850 Merge pull request #22055 from ChayimFriedman2/upvars-expr-store
fix: Some fixes for `upvars_mentioned()`
2026-04-19 02:22:07 +00:00
Chayim Refael Friedman
7c732dbd98 Support self upvar in upvars_mentioned() 2026-04-19 05:14:31 +03:00
Chayim Refael Friedman
0bb544a470 Support non-body expression store for upvars_mentioned() 2026-04-19 05:14:31 +03:00
Chayim Refael Friedman
6ac2dea600 Merge pull request #22084 from ada4a/debug-minicore
implement custom `Debug` for `MiniCore`
2026-04-19 02:04:22 +00:00
Daniel Scherzer
0cc3a7d6fe c-b: add missing word in src/mem/impls.rs docs 2026-04-18 21:42:33 -04:00
Guillaume Gomez
f658d2613c Remove AttributeLintKind::DocAutoCfgExpectsHideOrShow variant 2026-04-19 02:31:23 +02:00
Guillaume Gomez
0c93197a28 Remove AttributeLintKind::DuplicateDocAlias variant 2026-04-19 02:19:30 +02:00
Guillaume Gomez
ef3b800411 Remove AttributeLintKind::InvalidStyle variant 2026-04-19 02:11:28 +02:00
workflows-rust-analyzer[bot]
7d13144973 internal: update generated lints 2026-04-19 00:01:21 +00:00
Amanjeev Sethi
2720e65a68 Merge pull request #2839 from rust-lang/aj/rustc-internals-docs-clarity
Clarifications and instructions for nightly rustc internal docs.
2026-04-18 20:00:00 -04:00
Guillaume Gomez
52653ef1c6 Remove AttributeLintKind::InvalidTarget variant 2026-04-19 01:53:25 +02:00
bors
6f109d8a2d Auto merge of #155223 - teor2345:fndef-refactor, r=mati865
Refactor FnDecl and FnSig non-type fields into a new wrapper type





#### Why this Refactor?

This PR is part of an initial cleanup for the [arg splat experiment](https://github.com/rust-lang/rust/issues/153629), but it's a useful refactor by itself.

It refactors the non-type fields of `FnDecl`, `FnSig`, and `FnHeader` into a new packed wrapper types, based on this comment in the `splat` experiment PR:
https://github.com/rust-lang/rust/pull/153697#discussion_r3004637413

It also refactors some common `FnSig` creation settings into their own methods. I did this instead of creating a struct with defaults.

#### Relationship to `splat` Experiment

I don't think we can use functional struct updates (`..default()`) to create `FnDecl` and `FnSig`, because we need the bit-packing for the `splat` experiment.

Bit-packing will avoid breaking "type is small" assertions for commonly used types when `splat` is added.
This PR packs these types:
- ExternAbi: enum + `unwind` variants (38) -> 6 bits
- ImplicitSelfKind: enum variants (5) -> 3 bits
- lifetime_elision_allowed, safety, c_variadic: bool -> 1 bit

#### Minor Changes

Fixes some typos, and applies rustfmt to clippy files that got skipped somehow.
2026-04-18 23:46:37 +00:00
Guillaume Gomez
b4d02996f9 Remove AttributeLintKind::EmptyAttribute variant 2026-04-19 00:48:32 +02:00
Guillaume Gomez
5f0ccfba88 Remove AttributeLintKind::IllFormedAttributeInput variant 2026-04-19 00:36:20 +02:00
Amanjeev Sethi
369969a6c7 PR review: use better command 2026-04-18 18:25:35 -04:00
Ada Alakbarova
8463b33a01 implement custom Debug for MiniCore
When the contents correspond to the default, just output
`MiniCore("<default>")` instead of the whole thing.

Helps reduce the length of the debug output in the common case.
2026-04-18 22:35:30 +02:00
Ada Alakbarova
0b9410f728 refactor: merge RenderContext::is_deprecated and RenderContext::is_deprecated_assoc_item 2026-04-18 22:09:47 +02:00
Ada Alakbarova
02f0edc195 fix: also call is_deprecated on ModuleDef 2026-04-18 22:09:47 +02:00
Ada Alakbarova
3310c64da7 add tests
Note: the following def kinds were already handled correctly (deprecated=true):
- Variant
- Function
- Macro
2026-04-18 21:55:09 +02:00
Ada Alakbarova
28141750d7 misc improvements 2026-04-18 21:51:40 +02:00
bors
0febdbab27 Auto merge of #155494 - JonathanBrouwer:rollup-UvJjCP5, r=JonathanBrouwer
Rollup of 10 pull requests

Successful merges:

 - rust-lang/rust#150230 (spec next chunk for trustedlen)
 - rust-lang/rust#155284 (net::tcp/udp: fix docs about how set_nonblocking is implemented)
 - rust-lang/rust#146870 (fix: add aliasing rules for Box)
 - rust-lang/rust#154003 (Make std::fs::File Send on UEFI)
 - rust-lang/rust#155187 (std: fix HashMap RNG docs wording)
 - rust-lang/rust#155255 (Document why `layout.align() + layout.size()` doesn't overflow)
 - rust-lang/rust#155351 (Reorganize tests from `tests/ui/issues/`)
 - rust-lang/rust#155406 (std: Update dependency on `wasi` crate)
 - rust-lang/rust#155447 (Simplify `parse_limited`)
 - rust-lang/rust#155481 (Delete `SizeSkeleton::Generic`)
2026-04-18 19:16:28 +00:00
Ohad Ravid
2389a3a0fb Avoid unneeded work for storage removal in non-opt builds in CopyProp and GVN 2026-04-18 22:12:59 +03:00
Amanjeev Sethi
9faee77d93 Typo in crate name 2026-04-18 15:02:22 -04:00
Amanjeev Sethi
c5e1f600f5 Clarifications and instructions - nightly
- Only latest nightly crates' docs are published
- How to get an old nightly docs
2026-04-18 15:01:56 -04:00
nataliakokoromyti
9064d17405 Do not suggest borrowing enclosing calls for nested where-clause obligations 2026-04-18 10:51:16 -07:00
Jonathan Brouwer
403974738d Rollup merge of #155481 - theemathas:delete-size-skeleton-generic, r=scottmcm
Delete `SizeSkeleton::Generic`

This variant was never constructed anywhere.

r? @scottmcm
2026-04-18 19:23:18 +02:00
Jonathan Brouwer
c1657771be Rollup merge of #155447 - JonathanBrouwer:simplify-parse-limited, r=mejrs
Simplify `parse_limited`

Removes unnecessary arguments from `parse_limited` and cleans up feature gating of `on_unknown_attr`
2026-04-18 19:23:17 +02:00
Jonathan Brouwer
22aef0f0ae Rollup merge of #155406 - alexcrichton:update-wasi-deps, r=Mark-Simulacrum
std: Update dependency on `wasi` crate

This commit updates the crate dependency that the standard library has on the `wasi` crate. This is now updated to depending explicitly on the `wasip1` crate and the `wasip2` crate published on crates.io. These crates are managed in the [same location][repo] as the `wasi` crate and represent a different versioning scheme which doesn't require multi-version WASI support to require depending on the same crate at multiple versions. The code in libstd is updated to reference `wasip1` and `wasip2` directly as well.

[repo]: https://github.com/bytecodealliance/wasi-rs
2026-04-18 19:23:16 +02:00
Jonathan Brouwer
5c896555de Rollup merge of #155351 - ujjwalvishwakarma2006:reorg-tests-01, r=Kivooeo
Reorganize tests from `tests/ui/issues/`

The following tests are reorganized in this pull request

| old-name | new-sub-dir | new-name |
|-|-|-|
| `auxiliary/issue-2316-a.rs` | `resolve/auxiliary` | `resolve-conflict-local-vs-glob-import-a.rs` |
| `auxiliary/issue-2316-b.rs` | `resolve/auxiliary` | `resolve-conflict-local-vs-glob-import-b.rs` |
| `issue-2316-c.rs` | `resolve/` | `resolve-conflict-local-vs-glob-import.rs` |
| `issue-28839.rs` | `reborrow/` | `reborrow-mutable-reference.rs` |
| `issue-32008.rs` | `overloaded/` | `subtyping-both-lhs-and-rhs-in-add-impl.rs` |
| `issue-45425.rs` | `higher-ranked/` | `binop-lhs-hrtb-subtyping.rs` |

r? Kivooeo
2026-04-18 19:23:16 +02:00
Jonathan Brouwer
f0df37fac1 Rollup merge of #155255 - Zoxc:ub-issue-16, r=Mark-Simulacrum
Document why `layout.align() + layout.size()` doesn't overflow

This addition looks suspicious and is safety critical, but is saved by the weird `Layout` invariants.
2026-04-18 19:23:15 +02:00
Jonathan Brouwer
74fd4a720f Rollup merge of #155187 - ArshLabs:fix/hashmap-rng-doc-wording, r=Mark-Simulacrum
std: fix HashMap RNG docs wording

Fixes a wording typo in the top-level HashMap docs.

Changed "random number coroutine" to "random number generator" in the seed entropy paragraph.

This section is security-relevant, and "generator" is the correct term in RNG context.

Testing:
- Not run locally (docs-only text change).
2026-04-18 19:23:14 +02:00
Jonathan Brouwer
f7668674cc Rollup merge of #154003 - ginnyTheCat:uefi-file-send, r=Mark-Simulacrum
Make std::fs::File Send on UEFI

Similarly to rust-lang/rust#150990 since UEFI has no threads, this should be safe.
2026-04-18 19:23:14 +02:00
Jonathan Brouwer
92a2343356 Rollup merge of #146870 - DiuDiu777:box-doc-fix, r=Mark-Simulacrum
fix: add aliasing rules for Box

This is a new revised version for the PR [139857](https://github.com/rust-lang/rust/pull/139857), sorry for the delayed reply. I've rewritten the sentence to closely mirror the wording from `Vec::from_raw_parts`, which clearly states the transfer of ownership and its consequences. This should make the aliasing requirements much clearer.

I opted not to include a note about `mem::forget` by default to keep the documentation focused on the primary contract, similar to `Vec`.
2026-04-18 19:23:13 +02:00
Jonathan Brouwer
e28fb66f82 Rollup merge of #155284 - RalfJung:net-nonblocking, r=Mark-Simulacrum
net::tcp/udp: fix docs about how set_nonblocking is implemented

`fcntl` `FIONBIO` doesn't even make sense, it should be `fcntl` `F_SETFL`. However, for some reason we are using `ioctl` by default -- except on Solaris where this doesn't seem to work very well.

Honestly what I would have expected is that we just always use `FileDesc::set_nonblocking` also for network sockets, but for some reason we don't and there are no comments explaining this choice. Cc @nikarh (for "vita") @joboet
2026-04-18 19:23:12 +02:00
Jonathan Brouwer
77cbf96954 Rollup merge of #150230 - bend-n:trusted_len_spec_for_iter_next_chunk, r=Mark-Simulacrum
spec next chunk for trustedlen

relevant to rust-lang/rust#98326
2026-04-18 19:23:12 +02:00
Jonathan Brouwer
e0d7848e50 Fix rebox of directive 2026-04-18 19:15:18 +02:00
Jonathan Brouwer
5fe1e44dbb Clarify and make consistent the feature gating of on_unknown_attr 2026-04-18 19:13:34 +02:00
Jonathan Brouwer
c5f6afc3e8 Remove target arguments & features from parse_limited 2026-04-18 19:13:30 +02:00
Weihang Lo
d786ba8ca6 Update cargo submodule 2026-04-18 13:10:48 -04:00
Shun Sakai
8eb89a8b06 docs(num): fix stale link to mem::Alignment 2026-04-19 02:07:18 +09:00
bors
b2f1ccf524 Auto merge of #155258 - ShoyuVanilla:eq-constraint, r=lcnr
Make region equality emits Eq constraints



For context, see..

- The box named *coroutine witness Send lifetime requirements now considered by leakcheck* from [this roadmap](https://raw.githubusercontent.com/hexcatnl/roadmap/6f23e638f65249ef02af86a5454275103a71552d/next-solver.svg)
- [#t-types/trait-system-refactor > A question on #251 @ 💬](https://rust-lang.zulipchat.com/#narrow/channel/364551-t-types.2Ftrait-system-refactor/topic/A.20question.20on.20.23251/near/584166935)
- Comments on `rustc_type_ir::predicate::RegionEqPredicate`
2026-04-18 16:04:22 +00:00
Michael Howell
de48fc6a56 rustdoc: fix a few spots where emit isn't respected 2026-04-18 08:46:33 -07:00
Urgau
a755d0f4cb Add an edge-case test for --remap-path-prefix for rustc & rustdoc 2026-04-18 15:54:12 +02:00
Lukas Bergdoll
3a0c0e9cb7 Apply review feedback 2026-04-18 15:12:33 +02:00
Shoyu Vanilla
ace3aa319c Make region equality emits Eq constraints 2026-04-18 22:02:01 +09:00
bors
3142beae24 Auto merge of #155483 - JonathanBrouwer:rollup-9T12Udy, r=JonathanBrouwer
Rollup of 5 pull requests

Successful merges:

 - rust-lang/rust#155308 (Make `OnDuplicate::Error` the default for attributes)
 - rust-lang/rust#154432 (Set up API to make it possible to pass closures instead of `AttributeLint`)
 - rust-lang/rust#154843 (  Fix conflicting deref move suggestion for LazyLock patterns)
 - rust-lang/rust#155262 (bootstrap.py: fix duplicated "the")
 - rust-lang/rust#155478 (Fixed broken documentation link for method lookup in rustc_hir_typeck…)
2026-04-18 12:57:42 +00:00
Young-Flash
cdc1d7c058 internal: code review tweak 2026-04-18 20:40:30 +08:00
A4-Tacks
2dda8f6a40 Fix make.expr_closure invalid mappings 2026-04-18 19:01:14 +08:00
Jonathan Brouwer
963d61f0f9 Rollup merge of #155478 - Ollie-Pearce:fix-hir-method-lookup-doc-broken-link, r=mati865
Fixed broken documentation link for method lookup in rustc_hir_typeck…
2026-04-18 11:41:32 +02:00
Jonathan Brouwer
1336ecba0a Rollup merge of #155262 - DanielEScherzer:bootstrap-duplicate-the, r=Zalathar
bootstrap.py: fix duplicated "the"
2026-04-18 11:41:31 +02:00
Jonathan Brouwer
0e54c26ac8 Rollup merge of #154843 - nataliakokoromyti:fix-154826-deref-help, r=mati865
Fix conflicting deref move suggestion for LazyLock patterns

fixes rust-lang/rust#154826.

Rust was suggesting *V -> V for let (v,) = *V, which then triggered a follow-up error suggesting the opposite. This patch makes that case suggest borrowing (&*V) instead. Also handles destructuring assignment separately so we don’t emit a misleading &*... fix-it there.
2026-04-18 11:41:31 +02:00
Jonathan Brouwer
d12af208b9 Rollup merge of #154432 - GuillaumeGomez:try-rm-AttributeLint, r=JonathanBrouwer
Set up API to make it possible to pass closures instead of `AttributeLint`

Part of https://github.com/rust-lang/rust/issues/153099.

This PR sets up the base implementations needed to remove `AttributeLintKind` entirely and migrate two variants as examples.

r? @JonathanBrouwer
2026-04-18 11:41:30 +02:00
Jonathan Brouwer
eca0926c12 Rollup merge of #155308 - JonathanBrouwer:duplicate_errs, r=jdonszelmann
Make `OnDuplicate::Error` the default for attributes

This makes two changes, in separate commits for reviewability:
- Changes all unstable attributes that are currently `OnDuplicate::Warn` to error.
- Makes `OnDuplicate::Error` the default and removes the explicit `ON_DUPLICATE` for ones that currently already error

r? @jdonszelmann
2026-04-18 11:41:29 +02:00
bors
8da2d28cbd Auto merge of #142531 - ohadravid:better-storage-calls-copy-prop, r=tmiasko,cjgillot,saethlin
Remove fewer Storage calls in CopyProp and GVN



Modify the CopyProp and GVN MIR optimization passes to remove fewer `Storage{Live,Dead}` calls, allowing for better optimizations by LLVM - see rust-lang/rust#141649.

### Details

The idea is to use a new `MaybeUninitializedLocals` analysis and remove only the storage calls of locals that are maybe-uninit when accessed in a new location.
2026-04-18 09:16:07 +00:00
Theemathas Chirananthavat
1a27916756 Delete SizeSkeleton::Generic
This variant was never constructed anywhere.
2026-04-18 16:00:28 +07:00
Ollie
f9e7ede1ab Fixed broken documentation link for method lookup in rustc_hir_typeck::method 2026-04-18 09:20:56 +01:00
Jonathan Brouwer
0ff3fecf6f Make OnDuplicate::Error the default 2026-04-18 10:20:32 +02:00
Jonathan Brouwer
ae4cf84814 Mark all unstable attributes as OnDuplicate::Error 2026-04-18 10:20:32 +02:00
Zalathar
72abf370bb Rename incremental cfail/cpass revisions to bfail/bpass
Long ago, UI tests were divided into "compile" and "run" tests. Later, the
compile tests were further subdivided into "check" and "build" tests, to speed
up tests that don't need a full build.

The same split was never applied to incremental test revisions, so the only way
to perform a check build in incremental tests is (confusingly) to use a `cfail`
revision and then specify `//@ check-fail` or `//@ check-pass`.

This PR makes room for dedicated check-fail and check-pass revisions by
renaming the existing `cfail` and `cpass` revisions to `bfail` and `bpass`,
since they currently perform a full build.
2026-04-18 18:13:17 +10:00
Artem Ismagilov
607021cb1d add must_use macros
add msg
2026-04-18 11:23:14 +04:00
Zalathar
0ce1696dcf Adjust some outdated docs for //@ forbid-output 2026-04-18 17:17:02 +10:00
bors
7a38981b36 Auto merge of #155472 - jhpratt:rollup-cFOYOWJ, r=jhpratt
Rollup of 12 pull requests

Successful merges:

 - rust-lang/rust#147811 (naked functions: respect `function-sections`)
 - rust-lang/rust#154935 (Add Sized supertrait for CoerceUnsized and DispatchFromDyn)
 - rust-lang/rust#139690 (`impl Default for RepeatN`)
 - rust-lang/rust#153511 (`std::any::TypeId`: remove misplaced "and" in `Unique<T>` example)
 - rust-lang/rust#154943 (Move recursion out of `MatchPairTree::for_pattern` helpers )
 - rust-lang/rust#155295 (Fix misleading "borrowed data escapes outside of function" diagnostic)
 - rust-lang/rust#155427 (ptr: update text in intro text to one in with_addr doc)
 - rust-lang/rust#155428 (Fix ICE in borrowck mutability suggestion with multi-byte ref sigil)
 - rust-lang/rust#155435 (rustdoc: Fix `redundant_explicit_links` incorrectly firing (or not firing) under certain scenarios)
 - rust-lang/rust#155450 (Remove unnecessary safety conditions related to unchecked uint arithmetic)
 - rust-lang/rust#155454 (docs: Fix typo in std/src/thready/scoped.rs)
 - rust-lang/rust#155467 (`std::error::Request`: clean up documentation)
2026-04-18 05:00:37 +00:00
Jacob Pratt
0bfd952a27 Rollup merge of #155467 - DanielEScherzer:patch-2, r=mejrs
`std::error::Request`: clean up documentation
2026-04-18 00:05:22 -04:00
Jacob Pratt
4fa293c965 Rollup merge of #155454 - MadeInShineA:issue-155275-fix, r=lqd
docs: Fix typo in std/src/thready/scoped.rs

# Fix typo in std/src/thread/scoped.rs

## Why this pr

This PR fixes the typo mentioned in rust-lang/rust#155275.

I know this was originally fixed in rust-lang/rust#155325 and then in rust-lang/rust#155328.

But since the first issue was closed due to some ai slop and the second one was closed because the first one was already opened, it seems to me that this PR is still needed.

## What this pr does

This PR "just" fixes a typo inside the `std/src/thread/scoped.rs` file

Changing the comment from this:

```
/// borrow non-`'static` data from the outside the scope. See [`scope`] for
/// details.
```

to this:

```
/// borrow non-`'static` data from outside the scope. See [`scope`] for
/// details.
```
2026-04-18 00:05:21 -04:00
Jacob Pratt
0c326ece10 Rollup merge of #155450 - safer-rust:fix-doc2, r=jhpratt
Remove unnecessary safety conditions related to unchecked uint arithmetic

Improve the safety documentation of three unsafe APIs related to unsigned integer arithmetic.

- [unchecked_add](https://doc.rust-lang.org/nightly/core/primitive.usize.html#method.unchecked_add): It is impossible for `self + rhs < usize::MIN`.
- [unchecked_sub](https://doc.rust-lang.org/nightly/core/primitive.usize.html#method.unchecked_sub): It is impossible for `self - rhs > usize::MAX`.
- [unchecked_mul](https://doc.rust-lang.org/nightly/core/primitive.usize.html#method.unchecked_mul): It is impossible for `self * rhs < usize::MIN`.

The examples use `usize` for demonstration. All unsigned integer types suffer from the same issue because their APIs are generated by the same macro `uint_impl`, and fixing the macro documentation will fix them all.
2026-04-18 00:05:20 -04:00
Jacob Pratt
afb3f3d243 Rollup merge of #155435 - tonywu6:main, r=lolbinarycat
rustdoc: Fix `redundant_explicit_links` incorrectly firing (or not firing) under certain scenarios

Hi! I found some issues with the `rustdoc::redundant_explicit_links` lint while working on a personal project.

- After skipping a link that contains inline markups, the lint would incorrectly skip all the remaining links.

  For example, with the following snippet, the lint is fired for `[Option][Option]`, but not `[Result][Result]`:

  ```rs
  //! [Option][Option]
  //! [**u8**][u8]     (skipped)
  //! [Result][Result]
  ```

  Happening because of a `?` causing a loop to bail early:

  a4a37ed163/src/librustdoc/passes/lint/redundant_explicit_links.rs (L107)

- The lint is fired for links that specify titles (like `[link](link "title")`), except that wouldn't be applicable because it's not possible to specify a title without there also being an explicit target. For example:

  ```
  error: redundant explicit link target
  --> <anon>:5:12
    |
  5 | /// [drop](drop "This function is not magic")
    |      ----  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ explicit target is redundant
    |      |
    |      because label contains path that resolves to same destination
    |
    = note: when a link's destination is not specified,
            the label is used to resolve intra-doc links
  help: remove explicit link target
    |
  5 - /// [drop](drop "This function is not magic")
  5 + /// [drop]
    |
  ```

These are found as of:

```
rustdoc 1.97.0-nightly (1b8f2e46e 2026-04-17)
binary: rustdoc
commit-hash: 1b8f2e46e1
commit-date: 2026-04-17
host: aarch64-apple-darwin
release: 1.97.0-nightly
LLVM version: 22.1.2
```

(Note: I ran `./x test tests/rustdoc-ui` locally, but not `./x tidy` due to my slow internet. There was an unrelated failed test at `tests/rustdoc-ui/ice-bug-report-url.rs` which I'm not sure about)
2026-04-18 00:05:20 -04:00
Jacob Pratt
e3676b5ab9 Rollup merge of #155428 - lapla-cogito:issue_139089, r=mejrs
Fix ICE in borrowck mutability suggestion with multi-byte ref sigil

Fixes rust-lang/rust#139089

Similarly to rust-lang/rust#155068, this is another instance where span arithmetic did not account for multi-byte characters. (Note that the ampersand in the test is full-width)

This change also results in correcting some inappropriate suggestions.
2026-04-18 00:05:19 -04:00
Jacob Pratt
8b07a038cb Rollup merge of #155427 - tshepang:tshepang/match-text-in-with_addr, r=scottmcm
ptr: update text in intro text to one in with_addr doc

The one where this was copied from has since been updated.
2026-04-18 00:05:18 -04:00
Jacob Pratt
eb52efbbd2 Rollup merge of #155295 - lapla-cogito:issue_154350, r=JohnTitor
Fix misleading "borrowed data escapes outside of function" diagnostic

Fixes rust-lang/rust#154350

Fall back to `report_general_error()` when `fr_name_and_span` is `None` in function items, since the "escaping data" framing is only appropriate for closures capturing outside variables.
2026-04-18 00:05:18 -04:00
Jacob Pratt
eb185531e1 Rollup merge of #154943 - Zalathar:for-each-subpat, r=Nadrieril
Move recursion out of `MatchPairTree::for_pattern` helpers

The helper functions now just iterate over the relevant subpatterns, while leaving recursion up to the main function.

This avoids passing parameters that were only used for recursive plumbing, and consolidates all recursive calls into `for_pattern` itself, which should make it easier to experiment with changes to the recursive structure.

There should be no change to compiler behaviour.
2026-04-18 00:05:17 -04:00
Jacob Pratt
354bfa49ff Rollup merge of #153511 - DanielEScherzer:patch-3, r=scottmcm
`std::any::TypeId`: remove misplaced "and" in `Unique<T>` example
2026-04-18 00:05:17 -04:00
Jacob Pratt
221dab89b4 Rollup merge of #139690 - cuviper:iter_repeat_n_default, r=tgross35
`impl Default for RepeatN`

This creates an empty iterator, like `repeat_n(value, 0)` but without
needing any such value at hand. There's precedent in many other
iterators that the `Default` is empty, like `slice::Iter`.

I found myself wanting this for rayon's `RepeatN` as it lowers to a
sequential iterator [here][1]. Since rayon is also optimizing to avoid
extra clones, it may end up with parallel splits that have count 0 and
no item value. Calling `std::iter::repeat_n(x, 0)` just drops that
value, but there's no way to construct the same result without a value
yet. This would be straightforward with an empty `Default`.

[1]: ae07384e3e/src/iter/repeat.rs (L201-L202)

r? libs-api (insta-stable)
2026-04-18 00:05:16 -04:00
Jacob Pratt
db3d08421c Rollup merge of #154935 - Darksonn:dyn-trait-dyn-compat, r=scottmcm
Add Sized supertrait for CoerceUnsized and DispatchFromDyn

This is part of rust-lang/rust#149094. I did not include `Receiver` because I think it is correct to allow non-sized receivers.
2026-04-18 00:05:15 -04:00
Jacob Pratt
baf4388b8f Rollup merge of #147811 - folkertdev:naked-function-sections, r=Amanieu
naked functions: respect `function-sections`

fixes https://github.com/rust-lang/rust/issues/147789

r? @Amanieu
2026-04-18 00:05:15 -04:00
lapla
a779e054a9 Fix ICE in borrowck mutability suggestion with multi-byte ref sigil 2026-04-18 08:52:11 +09:00
Daniel Scherzer
1d1aa9a7fb std::error::Request: more documentation cleanup 2026-04-17 16:16:01 -07:00
León Orell Valerian Liehr
872a1c3cb8 Merge pull request #2838 from DanielEScherzer/patch-1
effects.md: update const trait syntax
2026-04-18 01:12:01 +02:00
Daniel Scherzer
873d2f6534 effects.md: update const trait syntax
`~const` was replaced with `[const]`, making uses of the former confusing
2026-04-17 16:04:49 -07:00
bors
2f201bccb3 Auto merge of #155404 - flip1995:clippy-subtree-update, r=Manishearth
Clippy subtree update

r? Manishearth 

`Cargo.lock` update due to Clippy version bump and cargo_metadata dep bump in Clippy.
2026-04-17 23:02:37 +00:00
Daniel Scherzer
6525e06475 std::error::Request: add missing period in docs
All but one of the bullet points ended with a period; add the missing period.
2026-04-17 15:54:12 -07:00
Guillaume Gomez
ded2eea3b2 Remove AttributeLintKind::UnusedDuplicate 2026-04-17 23:43:08 +02:00
Guillaume Gomez
c5b9918540 Set up API to make it possible to pass closures instead of AttributeLint.
The end goal being to completely remove `AttributeLint`.
2026-04-17 23:43:06 +02:00
Daniel Scherzer
e24dc1d1b8 tests/ui/extern: add annotations for reference rules 2026-04-17 14:05:57 -07:00
bors
e9e32aca5a Auto merge of #155432 - JonathanBrouwer:rollup-dJVrrO0, r=JonathanBrouwer
Rollup of 5 pull requests

Successful merges:

 - rust-lang/rust#154781 (Fix attribute order implementation)
 - rust-lang/rust#155242 (resolve: Introduce `(Local,Extern)Module` newtypes for local and external modules respectively)
 - rust-lang/rust#149614 (Use `MaybeDangling` in `std`)
 - rust-lang/rust#153178 (Add `TryFromIntError::kind` method and `IntErrorKind::NotAPowerOfTwo` variant)
 - rust-lang/rust#155049 (Documenting the case of `Weak::upgrade` returning `None` when the value behind the reference is missing)

Failed merges:

 - rust-lang/rust#155308 (Make `OnDuplicate::Error` the default for attributes)
2026-04-17 19:17:17 +00:00
Olivier Amacker
10cc6c4a39 docs: Fix typo in std/src/thread/scoped.rs 2026-04-17 19:39:18 +02:00
bors
f29256dd14 Auto merge of #155248 - JonathanBrouwer:no_hash_delayed_lints, r=GuillaumeGomez
Don't hash `DelayedLints`

This PR unblocks https://github.com/rust-lang/rust/pull/154432, and was also a minor perf win locally
2026-04-17 16:05:32 +00:00
A4-Tacks
19a8a2dfa9 Merge pull request #22077 from Albab-Hasan/fix-22072-if-let-match-paren-panic
fix: avoid panic in replace_if_let_with_match on jump scrutinee
2026-04-17 16:02:30 +00:00
aisr
d9c717783e remove unnecessary safety conditions related to unchecked uint arithmetic 2026-04-17 23:44:35 +08:00
Redddy
e2bb6fc0b1 Merge pull request rust-lang/rustc-dev-guide#2836 from reddevilmidzy/rr
Update link for Rust reference documentation
2026-04-18 00:18:36 +09:00
Redddy
72b21f4835 Update link for Rust reference documentation 2026-04-18 00:04:45 +09:00
albab-hasan
a0d8dd8f9d fix: wrap match scrutinee in parens when needed in replace_if_let_with_match
`if (return) {}` caused a panic in `replace_if_let_with_match`:
`let_and_guard` recursed through the `ParenExpr`, producing a bare
`return` as the scrutinee. `make::expr_match` formatted `match return
{ ... }`, which the parser reinterpreted as `match (return { ... })`,
consuming the arm list as the return value. The resulting match expr
had no `MatchArmList`, so the `unwrap()` in `SyntaxFactory::expr_match`
panicked.

Mirror the fix pattern from rust-lang/rust-analyzer#22067: build a fake
`match () { }` and ask whether the scrutinee needs parens in that
position via `needs_parens_in_place_of`. Wrap when required.

fixes rust-lang/rust-analyzer#22072
2026-04-17 20:47:59 +06:00
bjorn3
57966e987c Almost fully get rid of windows-sys 0.59
Only curl and stacker still depends on it.
2026-04-17 16:10:07 +02:00
Jonathan Brouwer
5c7384e1c9 Add regression test 2026-04-17 16:08:45 +02:00
Jonathan Brouwer
d14311c4a1 Don't hash DelayedLints 2026-04-17 16:08:45 +02:00
bjorn3
bed52c181d Get rid of windows-sys 0.60 in the main workspace 2026-04-17 16:06:36 +02:00
Ohad Ravid
5632001f83 Improve copy_prop and GVN mir-opt passes to remove fewer storage calls 2026-04-17 16:55:43 +03:00
Redddy
a43992e563 Merge pull request rust/rustc-dev-guide#2814 from erfanio/main
Update neovim instructions for neovim 0.11+
2026-04-17 21:25:42 +09:00
A4-Tacks
5642dfb887 fix: adjust name of extract_type_alias
Example
---
**Before this PR**

```rust
struct Type;
type $0Type = (u8, u8, u8);

struct S { field: Type }
```

**After this PR**

```rust
struct Type;
type $0Type1 = (u8, u8, u8);

struct S { field: Type1 }
```
2026-04-17 20:21:45 +08:00
Ralf Jung
47f6f0b7f2 Merge pull request #4967 from quiode/remove-vec_unique.default.stderr
remove vec_unique.default.stderr
2026-04-17 12:08:32 +00:00
Dominik Schwaiger
0560fdec40 remove vec_unique.default.stderr 2026-04-17 13:42:12 +02:00
Chayim Refael Friedman
8261351c8f Merge pull request #22074 from A4-Tacks/xtask-rsfmt-toolchain
internal: support RUSTFMT_TOOLCHAIN for xtask codegen
2026-04-17 11:38:30 +00:00
Jonathan Brouwer
f67a3759bf Rollup merge of #155049 - quixoticaxis:weak-upgrade-documentation-extension, r=jhpratt
Documenting the case of `Weak::upgrade` returning `None` when the value behind the reference is missing

Adds a clause to the documentation of `Weak` for `Arc` which was discussed in rust-lang/rust#154936.

Adds the same clause to the documentation of `Weak` for `Rc`, because the behavior is the same.
2026-04-17 13:28:59 +02:00
Jonathan Brouwer
932d807e7e Rollup merge of #153178 - sorairolake:feature/try-from-int-error-kind, r=tgross35
Add `TryFromIntError::kind` method and `IntErrorKind::NotAPowerOfTwo` variant

- ACP: rust-lang/libs-team#746
- Tracking issue: rust-lang/rust#153978

This pull request adds `kind` method to [`TryFromIntError`](https://doc.rust-lang.org/core/num/struct.TryFromIntError.html), which outputs the detailed cause of converting an integer failing.

This is primarily intended for use in cases where there are multiple causes for failure, such as converting from a large signed integer type to a small signed integer type.

At the moment, this method returns [`&IntErrorKind`](https://doc.rust-lang.org/core/num/enum.IntErrorKind.html). This type implements the `Copy` trait and could return `IntErrorKind`, but returns a reference to align with the behavior of [`ParseIntError::kind`](https://doc.rust-lang.org/core/num/struct.ParseIntError.html#method.kind). If it is not necessary to align the behavior of `TryFromIntError::kind` with `ParseIntError::kind`, I'll change this method to return `IntErrorKind`.

Before this pull request, `IntErrorKind` was only used by [`ParseIntError`](https://doc.rust-lang.org/core/num/struct.ParseIntError.html), but I changed it to be used by `TryFromIntError` as well, so I updated `IntErrorKind`'s documentation.

[`impl TryFrom<usize> for Alignment`](https://doc.rust-lang.org/std/ptr/struct.Alignment.html#impl-TryFrom%3Cusize%3E-for-Alignment) returns `TryFromIntError` as an error if the given value is not a power of two. However, `IntErrorKind` does not have a variant that represents this. So I added the variant `NotAPowerOfTwo` to represent this. For this variant to stabilize, both `try_from_int_error_kind` and `ptr_alignment_type` features must be stabilized.
2026-04-17 13:28:58 +02:00
Jonathan Brouwer
ea736ba569 Rollup merge of #149614 - WaffleLapkin:dangle-maybe, r=jhpratt
Use `MaybeDangling` in `std`

cc https://github.com/rust-lang/rust/issues/118166
2026-04-17 13:28:57 +02:00
Jonathan Brouwer
89bec2cd37 Rollup merge of #155242 - petrochenkov:modmodmod, r=mu001999
resolve: Introduce `(Local,Extern)Module` newtypes for local and external modules respectively

Right now both `LocalModule` and `ExternModule` refer to the same `ModuleData`, but the module data for local and extern modules can potentially be made quite different, and we can specialize name lookup for both cases as an optimization.

Declaration creation for local and external modules was already specialized as a part of the parallel import resolution work (see `define_local` and `define_extern`, rust-lang/rust#145108 and previous PRs), because they have different properties with regards to ownership and synchronization.
2026-04-17 13:28:56 +02:00
Jonathan Brouwer
c142d8013c Rollup merge of #154781 - JonathanBrouwer:fix-attr-order, r=jdonszelmann
Fix attribute order implementation

The implementation in https://github.com/rust-lang/rust/pull/153041 contained a mistake :c
I swapped the place where the error message was on, but did not change any code for which attribute was also selected, which explains the empty crater results.
**Interestingly, the original code is broken too, before https://github.com/rust-lang/rust/pull/153041 it always took the last attribute, regardless of what the `AttributeOrder` actually was...**

Let's first see crater results before making a decision

TODO for this PR: Make better tests for this
2026-04-17 13:28:55 +02:00
Tony Wu
b967de6255 rustdoc: fix issues with redundant_explicit_links 2026-04-17 19:17:42 +08:00
bors
4dbafc340b Auto merge of #153955 - aerooneqq:def-path-hash-collision, r=petrochenkov
delegation: fix def path hash collision, add per parent disambiguators



This PR addresses the following delegation issues:
- It fixes rust-lang/rust#153410 when generating new `DefId`s for generic parameters by ~saving `DisambiguatorState`s from resolve stage and using them at AST -> HIR lowering~ introducing per owner disambiguators and transferring them to AST -> HIR lowering stage
- ~Next it fixes the ICE which is connected to using `DUMMY_SP` in delegation code, which was found during previous fix~
- ~Finally, after those fixes the rust-lang/rust#143498 is also fixed, only bugs with propagating synthetic generic params are left.~

Fixes rust-lang/rust#153410. Part of rust-lang/rust#118212.

r? @petrochenkov
2026-04-17 11:13:11 +00:00
Chayim Refael Friedman
55e0d9d293 Merge pull request #22073 from Albab-Hasan/fix-22071-empty-block-comment-panic
fix: handle empty `/**/` in block_to_line assist
2026-04-17 11:10:25 +00:00
Lukas Bergdoll
e0ef87f880 Add temporary scope to assert_matches
Addresses https://github.com/rust-lang/rust/issues/154406 in part.
assert_eq will be done in a separate PR.
2026-04-17 13:04:29 +02:00
A4-Tacks
ab704f43bb internal: support RUSTFMT_TOOLCHAIN for xtask codegen 2026-04-17 18:39:00 +08:00
Jonathan Brouwer
6f968782fd Add regression tests 2026-04-17 12:37:58 +02:00
albab-hasan
85f2d15011 fix: return canonical short prefix from Comment::prefix
`Comment::prefix` iterated `CommentKind::BY_PREFIX` forward, so `/**/`
matched the `/**/` entry itself and returned the full 4-char string.
`block_to_line` then computed `&text[4..text.len()-2]` = `&text[4..2]`
and panicked.

Delegate `Comment::prefix` to `CommentKind::prefix`, which already
iterates in reverse and returns the canonical short form (`/*` for
non-doc block comments). The `/**/` and `/***` entries in `BY_PREFIX`
are still needed for `from_text` to classify them as non-doc blocks.

fixes rust-lang/rust-analyzer#22071
2026-04-17 16:37:45 +06:00
Vadim Petrochenkov
61bc404458 resolve: Introduce (Local,Extern)Module newtypes for local and external modules respectively 2026-04-17 13:09:04 +03:00
Tshepang Mbambo
9b36d40819 ptr: update text in intro text to one in with_addr doc
The one where this was copied from has since been updated.
2026-04-17 12:03:58 +02:00
Folkert de Vries
2db9de3782 add ignore-cross-compile to run-make test 2026-04-17 11:25:58 +02:00
Chayim Refael Friedman
31d47e7cbf Merge pull request #22069 from A4-Tacks/redundant-make-call
internal: remove redundant editor.make() calls
2026-04-17 08:16:57 +00:00
A4-Tacks
fa6376e63f internal: remove redundant editor.make() calls 2026-04-17 16:06:29 +08:00
Chayim Refael Friedman
2782382e58 Merge pull request #22067 from A4-Tacks/let-with-iflet-parens-record
fix: add parentheses on record expr for replace_let_with_if_let
2026-04-17 07:58:31 +00:00
Sergey Ivanov
f580872fe2 Extended the documentation for Arc's Weak::upgrade 2026-04-17 07:47:34 +00:00
bors
27dbdb57a2 Auto merge of #155416 - Zalathar:rollup-D1EWnrR, r=Zalathar
Rollup of 19 pull requests

Successful merges:

 - rust-lang/rust#141633 (Suggest to bind `self.x` to `x` when field `x` may be in format string)
 - rust-lang/rust#152980 (c-variadic: fix implementation on `avr`)
 - rust-lang/rust#154491 (Extend `core::char`'s documentation of casing issues (and fix a rustdoc bug))
 - rust-lang/rust#155318 (Use mutable pointers for Unix path buffers)
 - rust-lang/rust#155335 (Bump bootstrap to 1.96 beta)
 - rust-lang/rust#155354 (Remove AttributeSafety from BUILTIN_ATTRIBUTES)
 - rust-lang/rust#154970 (rustdoc: preserve `doc(cfg)` on locally re-exported type aliases)
 - rust-lang/rust#155095 (changed the information provided by (mut x) to mut x (Fix 155030))
 - rust-lang/rust#155305 (Make `convert_while_ascii` unsafe)
 - rust-lang/rust#155358 (ImproperCTypes: Move erasing_region_normalisation into helper function)
 - rust-lang/rust#155377 (tests/debuginfo/basic-stepping.rs: Remove FIXME related to ZSTs)
 - rust-lang/rust#155383 (Rearrange `rustc_ast_pretty`)
 - rust-lang/rust#155384 (triagebot: notify on diagnostic attribute changes)
 - rust-lang/rust#155386 (Use `box_new` diagnostic item for Box::new suggestions)
 - rust-lang/rust#155391 (Small refactor of `QueryJob::latch` method)
 - rust-lang/rust#155395 (Tweak how the "copy path" rustdoc button works to allow some accessibility tool to work with rustdoc)
 - rust-lang/rust#155396 (`as_ref_unchecked` docs link fix)
 - rust-lang/rust#155411 (compiletest: Remove the `//@ should-ice` directive)
 - rust-lang/rust#155413 (fix: typo in `std::fs::hard_link` documentation)
2026-04-17 07:35:43 +00:00
A4-Tacks
1b66051805 fix: add parentheses on record expr for replace_let_with_if_let
Example
---
```rust
fn main() {
    $0let x = Foo { x };
}
```

**Before this PR**

```rust
fn main() {
    if let x = Foo {
    }
}
```

**After this PR**

```rust
fn main() {
    if let x = (Foo { x }) {
    }
}
```
2026-04-17 15:32:53 +08:00
aerooneqq
699eb29443 Fix delegation def path hash collision, add per-parent disambiguators 2026-04-17 09:46:54 +03:00
Stuart Cook
9de2e2bfd7 Rollup merge of #155413 - StepfenShawn:patch-2, r=ChrisDenton
fix: typo in `std::fs::hard_link` documentation

Change "corresponds the" to "corresponds to the" in the documentation for `std::fs::hard_link`.
2026-04-17 16:18:02 +10:00
Stuart Cook
87315a8a53 Rollup merge of #155411 - Zalathar:should-ice, r=jieyouxu
compiletest: Remove the `//@ should-ice` directive

The `//@ should-ice` directive was only being used by one test, which can just as easily use the more general `//@ failure-status` directive instead.

All of the removed exit-code checks were redundant with other exit-code checks that are still present.

---

I have manually verified that `tests/incremental/delayed_span_bug.rs` fails if the failure-status directive is modified or removed.
2026-04-17 16:18:01 +10:00
Stuart Cook
fd57bed92e Rollup merge of #155396 - oconnor663:link_typo, r=folkertdev
`as_ref_unchecked` docs link fix

Fix what's probably a copy-paste-o in a docs link.
2026-04-17 16:18:01 +10:00
Stuart Cook
f92c79e3e0 Rollup merge of #155395 - GuillaumeGomez:copy-path-with-ronga, r=notriddle
Tweak how the "copy path" rustdoc button works to allow some accessibility tool to work with rustdoc

Fixes https://github.com/rust-lang/rust/issues/155032.

It's a bit better in term of "fragility" to retrieve this information: no need to parse text anymore, just to retrieve content. However it relies on HTML. I added extra tests to ensure it won't break without notice.

cc @Enyium

r? @lolbinarycat
2026-04-17 16:18:00 +10:00
Stuart Cook
7e43cdf977 Rollup merge of #155391 - zetanumbers:query_latch_oneliner, r=petrochenkov
Small refactor of `QueryJob::latch` method

We can use `Option::get_or_insert_with` to avoid unwrapping there.
2026-04-17 16:17:59 +10:00
Stuart Cook
b9d3efa317 Rollup merge of #155386 - cijiugechu:fix-box-new-diagnostic-item, r=Kivooeo
Use `box_new` diagnostic item for Box::new suggestions

When look this part of code, I noticed this FIXME and fixed it :)
2026-04-17 16:17:58 +10:00
Stuart Cook
37344ab259 Rollup merge of #155384 - mejrs:pingme, r=jieyouxu
triagebot: notify on diagnostic attribute changes

Did I get this right? 😆
2026-04-17 16:17:58 +10:00
Stuart Cook
f9c4e61ac0 Rollup merge of #155383 - nnethercote:rearrange-rustc_ast_pretty, r=WaffleLapkin
Rearrange `rustc_ast_pretty`

`rustc_ast_pretty` has two modules, `pp::convenience` and `helpers`, that are small and silly. This PR eliminates them. Details in the individual commits.

r? @WaffleLapkin
2026-04-17 16:17:57 +10:00
Stuart Cook
36351e1485 Rollup merge of #155377 - Enselic:stepping-zsts, r=petrochenkov
tests/debuginfo/basic-stepping.rs: Remove FIXME related to ZSTs

We don't consider it a bug that users can't break on initialization of some non-zero sized types (see https://github.com/rust-lang/rust/pull/153941 and linked discussions), so it does not make sense to consider it a bug that users can't break on initialization of some zero-sized types.

Closes rust-lang/rust#97083

r? compiler (see https://github.com/rust-lang/rust/pull/155352)
2026-04-17 16:17:56 +10:00
Stuart Cook
e59e8f0412 Rollup merge of #155358 - niacdoial:improperctypes-refactor2.1, r=petrochenkov
ImproperCTypes: Move erasing_region_normalisation into helper function

This is "part 1/3 of 2/3 of 1/2" of the original pull request https://github.com/rust-lang/rust/pull/134697 (refactor plus overhaul of the ImproperCTypes family of lints)
(all pulls of this series of pulls are supersets of the previous pulls. If this pull is "too small" to be worth the effort, you can instead look at the next in the series)

This pull is a small internal change among the efforts to refactor the ImproperCTypes lints, by moving some "unwrapping" code (`cx.tcx.try_normalize_erasing_regions`) into a helper function.

r? petrochenkov
2026-04-17 16:17:55 +10:00
Stuart Cook
16b22a7e0f Rollup merge of #155305 - Zoxc:ub-issue-2, r=tgross35
Make `convert_while_ascii` unsafe

`convert_while_ascii` assumes `convert` only returns ASCII to ensure the output remains valid UTF-8. This adds that requirement as a safety precondition.
2026-04-17 16:17:55 +10:00
Stuart Cook
350e0d7fad Rollup merge of #155095 - lms0806:issue_155030, r=nnethercote
changed the information provided by (mut x) to mut x (Fix 155030)

When trying to change a value without using mut in a for loop, the recommendation for this change is incorrect, so I am correcting it.

resolve: rust-lang/rust#155030
2026-04-17 16:17:54 +10:00
Stuart Cook
0ab3a69f3c Rollup merge of #154970 - shivendra02467:fix-rustdoc-154921, r=GuillaumeGomez
rustdoc: preserve `doc(cfg)` on locally re-exported type aliases

When a type alias is locally re-exported from a private module (an implicit inline), rustdoc drops its `cfg` attributes because it treats it like a standard un-inlined re-export. Since type aliases have no inner fields to carry the `cfg` badge (unlike structs or enums), the portability info is lost entirely.

This patch explicitly preserves the target's `cfg` metadata when the generated item is a `TypeAliasItem`, ensuring the portability badge renders correctly without breaking standard cross-crate re-export behavior.

Fixes rust-lang/rust#154921
2026-04-17 16:17:53 +10:00
Stuart Cook
d4b573d95c Rollup merge of #155354 - JonathanBrouwer:attr-safety-port-2, r=mejrs
Remove AttributeSafety from BUILTIN_ATTRIBUTES

Encodes the expected attribute safety in the attribute parsers, rather than in `BUILTIN_ATTRIBUTES`, with the goal of removing `BUILTIN_ATTRIBUTES` soon.
We can remove the old attribute safety logic already because unparsed attributes, just like the as of yet unparsed lint attributes, need to be safe.

r? @jdonszelmann  (or @mejrs if you feel like doing it, since you are in T-compiler now 🎉)
2026-04-17 16:17:53 +10:00
Stuart Cook
6951f83914 Rollup merge of #155335 - Mark-Simulacrum:bootstrap-bump, r=jieyouxu
Bump bootstrap to 1.96 beta

See https://forge.rust-lang.org/release/process.html#default-branch-bootstrap-update-tuesday

I think this will wind up needing another PR in a week or so when we pick up assert_matches getting destabilized in beta? But that seems like it can be split into its own PR.
2026-04-17 16:17:52 +10:00
Stuart Cook
b7ea9df119 Rollup merge of #155318 - Zoxc:ub-issue-50, r=ChrisDenton
Use mutable pointers for Unix path buffers

This gets mutable pointers for Unix path buffers to ensure they have the right provenance.
2026-04-17 16:17:51 +10:00
Stuart Cook
3c61fba50b Rollup merge of #154491 - Jules-Bertholet:case-docs, r=Mark-Simulacrum,GuillaumeGomez
Extend `core::char`'s documentation of casing issues (and fix a rustdoc bug)

@rustbot label A-unicode A-docs
2026-04-17 16:17:50 +10:00
Stuart Cook
91a7d1b498 Rollup merge of #152980 - folkertdev:c-variadic-avr, r=tgross35
c-variadic: fix implementation on `avr`

tracking issue: https://github.com/rust-lang/rust/issues/44930
cc target maintainer @Patryk27

I ran into multiple issues, and although with this PR and a little harness I can run the test with qemu on avr, the implementation is perhaps not ideal.

The problem we found is that on `avr` the `c_int/c_uint` types are `i16/u16`, and this was not handled in the c-variadic checks. Luckily there is a field in the target configuration that contains the targets `c_int_width`. However, this field is not actually used in `core` at all, there the 16-bit targets are just hardcoded.

1500f0f47f/library/core/src/ffi/primitives.rs (L174-L185)

Perhaps we should expose this like endianness and pointer width?

---

Finally there are some changes to the test to make it compile with `no_std`.
2026-04-17 16:17:50 +10:00
Stuart Cook
1ff95e018f Rollup merge of #141633 - xizheyin:issue-141350, r=nnethercote
Suggest to bind `self.x` to `x` when field `x` may be in format string

Fixes rust-lang/rust#141350

I added the new test in the first commit, and committed the changes in the second one.

r? @fmease
cc @mejrs
2026-04-17 16:17:49 +10:00
Lukas Wirth
1ff215221b Bump salsa 2026-04-17 07:37:15 +02:00
Chayim Refael Friedman
1c8738f664 Merge pull request #22066 from ChayimFriedman2/std-test
fix: Recognize `#[std::prelude::vX::test]` (not just `#[core::prelude::vX::test]`
2026-04-17 05:24:23 +00:00
Chayim Refael Friedman
86c3c777d4 Recognize #[std::prelude::vX::test] (not just #[core::prelude::vX::test] 2026-04-17 08:15:10 +03:00
Shun Sakai
c35ed1ac32 feat: Add TryFromIntError::kind and IntErrorKind::NotAPowerOfTwo 2026-04-17 14:04:56 +09:00
bors
1b8f2e46e1 Auto merge of #155207 - quiode:writable, r=RalfJung
add llvm writable attribute conditionally




This PR tries to address https://github.com/rust-lang/unsafe-code-guidelines/issues/584#issue-3440604811. It is part of a bachelor thesis supervised by @JoJoDeveloping and @RalfJung, for more information, see: [Project_Description.pdf](https://github.com/user-attachments/files/26537277/Project_Description.pdf).
If the new `-Zllvm-writable` flag is set, the [llvm writable attribute](https://llvm.org/docs/LangRef.html#writable) is inserted for all mutable borrows. This can be conditionally turned off on a per-function basis using the `#[rustc_no_writable]` attribute. The new Undefined Behaviour introduced by this can detected by Miri, which is implemented here: https://github.com/rust-lang/miri/pull/4947.

Two library functions already received the `#[rustc_no_writable]` attribute, as they are known to cause problems under the Tree Borrows aliasing model with implicit writes enabled.
2026-04-17 04:13:36 +00:00
🍌Shawn
b05e29b8cb Fix typo in documentation for CreateHardLink function 2026-04-17 11:52:59 +08:00
Zalathar
975402e329 Remove the //@ should-ice directive
This directive was only being used by one test, which can just as easily use
the more general `//@ failure-status` directive instead.

All of the removed exit-code checks were redundant with other exit-code checks
that are still present.
2026-04-17 13:43:50 +10:00
Chayim Refael Friedman
d1fd8810d5 Merge pull request #22043 from Shourya742/2026-04-14-migrate-make-with-syntax-editor-in-raw-string
Replace make with syntax factory in raw string handler
2026-04-17 01:15:04 +00:00
Chayim Refael Friedman
f880529c47 Merge pull request #22065 from ChayimFriedman2/fix-clippy
internal: Fix 1.95.0 Clippy
2026-04-17 01:14:25 +00:00
Chayim Refael Friedman
fa147019d0 Fix 1.95.0 Clippy
Quite a lot of false positives this time.
2026-04-17 03:51:50 +03:00
Josh Stone
a66b7810c3 impl Default for RepeatN
This creates an empty iterator, like `repeat_n(value, 0)` but without
needing any such value at hand. There's precedent in many other
iterators that the `Default` is empty, like `slice::Iter`.

I found myself wanting this for rayon's `RepeatN` as it lowers to a
sequential iterator [here][1]. Since rayon is also optimizing to avoid
extra clones, it may end up with parallel splits that have count 0 and
no item value. Calling `std::iter::repeat_n(x, 0)` just drops that
value, but there's no way to construct the same result without a value
yet. This would be straightforward with an empty `Default`.

[1]: ae07384e3e/src/iter/repeat.rs (L201-L202)
2026-04-16 16:49:11 -07:00
Mark Rousskov
a64c420c70 Bump stage0 to 1.96 beta 2026-04-16 19:30:56 -04:00
John Kåre Alsaker
7a47964d3f Use mutable pointers for Unix path buffers 2026-04-17 01:08:08 +02:00
Trevor Gross
5d4b1764c1 bench: Use a group with many benches rather than many groups 2026-04-16 18:18:54 -04:00
bors
0204aca066 Auto merge of #155385 - davidtwco:stdarch-sync-160426, r=davidtwco
stdarch subtree update

Subtree update of `stdarch` to 095646219d.

Created using https://github.com/rust-lang/josh-sync.

r? @ghost
2026-04-16 21:38:27 +00:00
Spxg
dcb70deadf Fix the type of CmpResult on wasm64
resolve rust-lang/compiler-builtins#1199
2026-04-16 17:27:08 -04:00
Alex Crichton
690be3e13c std: Update dependency on wasi crate
This commit updates the crate dependency that the standard library has
on the `wasi` crate. This is now updated to depending explicitly on the
`wasip1` crate and the `wasip2` crate published on crates.io. These
crates are managed in the [same location][repo] as the `wasi` crate and
represent a different versioning scheme which doesn't require
multi-version WASI support to require depending on the same crate at
multiple versions. The code in libstd is updated to reference `wasip1`
and `wasip2` directly as well.

[repo]: https://github.com/bytecodealliance/wasi-rs
2026-04-16 14:11:28 -07:00
Guillaume Gomez
6c4ec59d5f Tweak how the "copy path" rustdoc button works to allow some accessibility tool to work with rustdoc 2026-04-16 22:06:45 +02:00
Philipp Krones
eee5e1a8bd Fix Clippy lint in bootstrap 2026-04-16 20:20:52 +02:00
bors
7af3402cda Auto merge of #155380 - jhpratt:rollup-j1e7DVL, r=jhpratt
Rollup of 18 pull requests

Successful merges:

 - rust-lang/rust#154451 (Require that a `<_ as Try>::Residual` implement the `Residual` trait)
 - rust-lang/rust#154595 (Emit fatal on invalid const args with nested defs)
 - rust-lang/rust#154599 (report the `varargs_without_pattern` lint in deps)
 - rust-lang/rust#154699 (`core::unicode`: Replace `Cased` table with `Lt`)
 - rust-lang/rust#155353 (resolve: Remove `inaccessible_ctor_reexport` resolver field)
 - rust-lang/rust#155357 (Add `--remap-path-scope` as unstable in rustdoc)
 - rust-lang/rust#150649 (clippy fix: non_canonical_clone_impl)
 - rust-lang/rust#154604 (abort in core)
 - rust-lang/rust#154616 (Add `--quiet` flag to x.py and bootstrap to suppress output)
 - rust-lang/rust#155215 (Clean up `AttributeLintKind` and refactor diagnostic attribute linting)
 - rust-lang/rust#155228 (Check diagnostic output in incremental `cpass` and `rpass` revisions)
 - rust-lang/rust#155266 (Adjust release notes for post-merge feedback)
 - rust-lang/rust#155326 (Disallow ZST allocations with `TypedArena`.)
 - rust-lang/rust#155334 (docs: Use `0b1` instead of `NonZero::MIN` in `NonZero::bit_width` doctests)
 - rust-lang/rust#155340 (Handle nonnull pattern types in size skeleton)
 - rust-lang/rust#155347 (Add push_mut and new Layout methods to release notes)
 - rust-lang/rust#155356 (remove calls to AliasTyKind::def_id)
 - rust-lang/rust#155364 (Reduce diagnostic type visibilities.)
2026-04-16 18:19:58 +00:00
gamma0987
32ccc13554 fix: Remove duplicate icount_bench_gef128_group in libm-test benches 2026-04-16 14:03:15 -04:00
Trevor Gross
c7c1c1a8d0 c-b: Better document where CmpResult comes from 2026-04-16 13:52:11 -04:00
Philipp Krones
760db10f1e Update Cargo.lock 2026-04-16 19:49:04 +02:00
Philipp Krones
55b8a36196 Merge commit 'f6d310692116e9a527ce6d0b3526c965d9c5d7b9' into clippy-subtree-update 2026-04-16 19:48:14 +02:00
Mend Renovate
b61f1716c7 chore(deps): update rust crate gungraun to 0.18.0 2026-04-16 13:44:34 -04:00
Philipp Krones
f6d3106921 Rustup (#16866)
r? @ghost

changelog: none
2026-04-16 17:19:29 +00:00
Philipp Krones
7a697630f4 Bump Clippy version -> 0.1.97 2026-04-16 19:13:51 +02:00
Philipp Krones
a6fceda49e Bump nightly version -> 2026-04-16 2026-04-16 19:13:43 +02:00
Philipp Krones
205fab6b0f Merge remote-tracking branch 'upstream/master' into rustup 2026-04-16 19:13:25 +02:00
Samuel Tardieu
121f867042 Do not trigger let_and_return on let else (#16829)
changelog: [`let_and_return_on`]: do not trigger on `let else` construct

Fixes rust-lang/rust-clippy#16820
2026-04-16 15:37:47 +00:00
Ralf Jung
9b9dc0709d Merge pull request #4966 from RalfJung/help
fix 'cargo miri nextest <verb> --help' output
2026-04-16 15:11:53 +00:00
Jack O'Connor
b2d24051be as_ref_unchecked docs link fix 2026-04-16 08:03:23 -07:00
bors
d227e48c56 Auto merge of #155393 - ehuss:fix-1.95-changelog, r=Mark-Simulacrum
Fix version number in releases for 1.95.0

The incomplete version number prevented the GitHub Release from being generated.
2026-04-16 14:51:56 +00:00
Ralf Jung
fabc30d05b fix 'cargo miri nextest <verb> --help' output 2026-04-16 16:44:09 +02:00
Eric Huss
e27f84a68c Fix version number in releases for 1.95.0
The incomplete version number prevented the GitHub Release from being
generated.
2026-04-16 07:02:05 -07:00
mejrs
4645f036d0 triagebot: notify on diagnostic attribute changes 2026-04-16 15:48:06 +02:00
Philipp Krones
a333abf7c5 Changelog for Clippy 1.95 (#16842)
Violets are red,
Roses are blue,
This month brings rain,
and sunshine peeks through.

----

Alexa from @bestman8

<img width="1080" height="1616" alt="image"
src="https://github.com/user-attachments/assets/eb86a6d2-427c-441c-ad03-1c0ace63128d"
/>

<br/>
<br/>
and
<br/>
<br/>
Ichigo from @oupson

<img width="1637" height="2214" alt="image"
src="https://github.com/user-attachments/assets/c8610a1b-6bce-453d-aefb-0c906ca6940c"
/>

are the winners at https://github.com/rust-lang/rust-clippy/pull/16653

P.S. Since there was no voting, picked the one with more hearts

----

Cats for the next release can be nominated in the comments🙏

changelog: none

r? flip1995
2026-04-16 13:39:33 +00:00
Lukas Wirth
55801602fb Merge pull request #22063 from Veykril/push-zyrytxqturpp
Remove `LineIndexDatabase`
2026-04-16 12:39:26 +00:00
Lukas Wirth
b4fc58d316 Remove LineIndexDatabase 2026-04-16 14:30:38 +02:00
Dominik Schwaiger
da2bbfbbec add llvm writable attribute conditionally 2026-04-16 12:29:39 +00:00
Daria Sukhonina
d0f5b5caa8 Replace redundant unwrap with get_or_insert_with 2026-04-16 15:19:42 +03:00
bors
18b439f84e Auto merge of #154605 - estebank:attr-suggest, r=jieyouxu
Make `span_suggestions` always verbose



`span_suggestions` is to provide mutually exclusive suggestions. When it was introduced, we made its behavior be that if a single suggestion is given to it, we present the suggestion inline, otherwise in patch format. Changing this to make all of its uses be verbose, as that is closer in intent of output.
2026-04-16 11:23:18 +00:00
Zalathar
fb27b3b7a7 Simplify macros for target-modifier and mitigation flags 2026-04-16 21:01:26 +10:00
cijiugechu
78a465a86d Use box_new diagnostic item for Box::new suggestions 2026-04-16 18:09:36 +08:00
Folkert de Vries
a875e140b6 c-variadic: make VaArgSafe a lang item
so that we can check whether a type implements the trait
2026-04-16 11:48:06 +02:00
Folkert de Vries
b8ba4002f5 c-variadic: handle c_int being i16 and c_double being f32 on avr 2026-04-16 11:48:02 +02:00
Folkert de Vries
41afd5f8d6 handle uefi and test assembly versus regular functions 2026-04-16 11:37:46 +02:00
Folkert de Vries
cc1ebb5e20 add uefi to windows link section test 2026-04-16 11:37:46 +02:00
Folkert de Vries
7787bd915b fix macho section specifier & windows test 2026-04-16 11:37:46 +02:00
Folkert de Vries
bc4aad37ca naked-functions: properly document the -Zfunction-sections windows status 2026-04-16 11:37:45 +02:00
Folkert de Vries
25e1647869 naked functions: add run-make test for DCE 2026-04-16 11:37:45 +02:00
Folkert de Vries
872301bfdd naked functions: respect function_sections on linux/macos 2026-04-16 11:37:45 +02:00
Folkert de Vries
0e522d6c62 naked functions: respect function_sections on windows
For `gnu` function_sections is off by default.
2026-04-16 11:37:45 +02:00
Trevor Gross
b2877ac70d ci: Exclude update-api-list from libm tests 2026-04-16 05:24:29 -04:00
Nicholas Nethercote
9e940e4051 Merge Printer impl blocks.
`rustc_ast_pretty::pp` defines `Printer` and has a 346 line `impl
Printer` block for it. `rustc_ast_pretty::pp::convenience` has another
`impl Printer` block with 85 lines. `rustc_ast_pretty::helpers` has
another `impl Printer` block with 45 lines.

This commit merges the two small `impl Printer` blocks into the bigger
one, because there is no good reason for them to be separate. Doing this
eliminates the `rustc_ast_pretty::pp::convenience` and
`rustc_ast_pretty::helpers` modules; no great loss given that they were
small and had extremely generic names.
2026-04-16 18:22:56 +10:00
Nicholas Nethercote
0529b94578 Move Token impl block.
For no apparent reason it's in a different file to `Token` itself. This
commit moves it.
2026-04-16 18:19:41 +10:00
teor
a70f37baa6 fixup! Refactor FnDecl and FnSig flags into packed structs 2026-04-16 16:28:59 +10:00
Shivendra Sharma
52ad8c071c rustdoc: preserve doc(cfg) on locally re-exported type aliases
When a type alias is locally re-exported from a private module (an implicit
inline), rustdoc drops its `cfg` attributes because it treats it like a
standard un-inlined re-export. Since type aliases have no inner fields to
carry the `cfg` badge (unlike structs or enums), the portability info
is lost entirely.

This patch explicitly preserves the target's `cfg` metadata when the
generated item is a `TypeAliasItem`, ensuring the portability badge
renders correctly without breaking standard cross-crate re-export behavior.
2026-04-16 11:51:51 +05:30
Jacob Pratt
92f640115a Rollup merge of #155364 - nnethercote:reduce-err-struct-visibilities, r=Kivooeo
Reduce diagnostic type visibilities.

Most diagnostic types are only used within their own crate, and so have a `pub(crate)` visibility. We have some diagnostic types that are unnecessarily `pub`. This is bad because (a) information hiding, and (b) if a `pub(crate)` type becomes unused the compiler will warn but it won't warn for a `pub` type.

This commit eliminates unnecessary `pub` visibilities for some diagnostic types, and also some related things due to knock-on effects. (I found these types with some ad hoc use of `grep`.)

r? @Kivooeo
2026-04-16 01:54:15 -04:00
Jacob Pratt
94d946ea69 Rollup merge of #155356 - WilliamTakeshi:remove_calls_to_def_id, r=WaffleLapkin
remove calls to AliasTyKind::def_id

ref https://github.com/rust-lang/rust/issues/154941

I asked the LSP where `AliasTyKind::def_id` and then checked where the `AliasTyKind::def_id` was trivial to change. Could only find 2 places, and I am not sure about the `opaque_types.rs` (open to feedback!! :) ). All the others need refactoring or will end up with a logic as complex as `AliasTyKind::def_id`

This is the list checked:
- [X] compiler/rustc_borrowck/src/region_infer/opaque_types/member_constraints.rs — 1
- [X] compiler/rustc_borrowck/src/region_infer/opaque_types/mod.rs — 1
- [X] compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs — 5
- [X] compiler/rustc_hir_analysis/src/check/mod.rs — 1
- [X] compiler/rustc_infer/src/infer/outlives/for_liveness.rs — 2
- [X] compiler/rustc_infer/src/infer/outlives/obligations.rs — 1
- [X] compiler/rustc_infer/src/infer/outlives/verify.rs — 3
- [X] compiler/rustc_middle/src/ty/print/pretty.rs — 1
- [X] compiler/rustc_middle/src/ty/sty.rs — 1
- [X] compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs — 3
- [X] compiler/rustc_next_trait_solver/src/solve/effect_goals.rs — 3
- [X] compiler/rustc_pattern_analysis/src/rustc.rs — 1
- [X] compiler/rustc_public/src/unstable/convert/stable/ty.rs — 1
- [X] compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs — 2
- [X] compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs — 4
- [X] compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs — 2
- [X] compiler/rustc_trait_selection/src/traits/effects.rs — 1
- [X] compiler/rustc_trait_selection/src/traits/query/normalize.rs — 1
- [X] compiler/rustc_ty_utils/src/opaque_types.rs — 7
- [X] compiler/rustc_ty_utils/src/ty.rs — 1
- [X] compiler/rustc_type_ir/src/outlives.rs — 1
- [X] compiler/rustc_type_ir/src/predicate.rs — 1
- [X] compiler/rustc_type_ir/src/relate.rs — 5
- [X] compiler/rustc_type_ir/src/ty_kind.rs — 2

r? @WaffleLapkin
2026-04-16 01:54:14 -04:00
Jacob Pratt
671cfed011 Rollup merge of #155347 - balt-dev:patch-1, r=cuviper
Add push_mut and new Layout methods to release notes

As recommended by @cuviper on Zulip, I'm making a direct PR to add this.
2026-04-16 01:54:14 -04:00
Jacob Pratt
a5f590a1d6 Rollup merge of #155340 - oli-obk:size-skeleton-pat-tys, r=mati865
Handle nonnull pattern types in size skeleton

The original comment was correct, the size is always the same, but we have more information now. In theory there was an additional bug that would have allowed transmuting things of different sizes, but I don't see how that would have been actually doable as the `tail` types would always have differed.

fixes rust-lang/rust#155330
2026-04-16 01:54:13 -04:00
Jacob Pratt
1798309c6e Rollup merge of #155334 - sorairolake:docs/nonzero-bit-width-literal, r=jhpratt
docs: Use `0b1` instead of `NonZero::MIN` in `NonZero::bit_width` doctests

This pull request updates the doctests for the `NonZero::bit_width` method. It replaces the use of the `NonZero::MIN` constant with an explicit binary literal `0b1`.

I think using `0b1` is more intuitive for illustrating the method's behavior than `NonZero::MIN`. Since other examples in the same doctests already use `0b111` and `0b1110`, this change brings the first example into alignment with the rest of the doctests.

I followed the existing pattern in the `NonZero::highest_one` and `NonZero::lowest_one` methods, which already use `0b1` in their doctests.

I also followed the convention of `uint::bit_width`, which uses the literal `0` instead of the `uint::MIN` constant in its doctests.
2026-04-16 01:54:13 -04:00
Jacob Pratt
52d6a1e376 Rollup merge of #155326 - nnethercote:disallow-ZST-TypedArena, r=Nadrieril
Disallow ZST allocations with `TypedArena`.

`DroplessArena::alloc` already disallows ZST allocation. `TypedArena::alloc` allows it but:
- (a) it's never used, and
- (b) writing to `NonNull::dangling()` seems dubious, even if the write is zero-sized.

This commit just changes it to panic on a ZST. This eliminates an untested code path, and we shouldn't be allocating ZSTs anyway. It also eliminates an unused ZST code path in `clear_last_chunk`.

r? @Nadrieril
2026-04-16 01:54:12 -04:00
Jacob Pratt
755465fcc2 Rollup merge of #155266 - Mark-Simulacrum:relnotes-fix, r=jieyouxu
Adjust release notes for post-merge feedback

* Adds musl CVE fix to compiler section
* Removes Cargo section per feedback in the PR (https://github.com/rust-lang/rust/pull/155162#discussion_r3073656171)

cc @BoxyUwU (just FYI)
2026-04-16 01:54:11 -04:00
Jacob Pratt
74bf79509b Rollup merge of #155228 - Zalathar:incr-test-diag, r=jieyouxu
Check diagnostic output in incremental `cpass` and `rpass` revisions

This allows compiler warnings to be annotated in `cpass` and `rpass` revisions, and verifies that no unexpected warnings occur.

---

My underlying motivation is that I want to be able to reduce or eliminate the confusing combination of `cfail` revisions with `//@ build-pass` directives, and replace them with a more straightforward `cpass` revision that also checks diagnostic output. That migration is not part of this PR.
2026-04-16 01:54:11 -04:00
Jacob Pratt
0d98e0d54f Rollup merge of #155215 - mejrs:condense_diag_lints, r=JonathanBrouwer
Clean up `AttributeLintKind` and refactor diagnostic attribute linting

There was a fair amount of duplication here, and thanks to the proliferation of new diagnostic attributes these days, it was threatening to grow bigger.
2026-04-16 01:54:10 -04:00
Jacob Pratt
fc3251a845 Rollup merge of #154616 - erickt:quiet, r=jieyouxu
Add `--quiet` flag to x.py and bootstrap to suppress output

This adds a `--quiet` flag to x.py and bootstrap to suppress some of the output when compiling Rust. It conflicts with `--verbose`, matching the behavior of `cargo` which does not allow `--verbose` and `--quiet`.

It works by passing quiet flags down to the underlying cargo, or LLVM build processes. Note that for LLVM, we only can suppress logs when we explicitly configure it with ninja. Otherwise we won't know what flag to pass along to whichever build system cmake decides to use.

This can be helpful with AI workloads in the Rust codebase to help shrink down the output to reduce token usage, which can help prevent context pollution and lower costs.

This patch was partially generated with Gemini, but I've reviewed the changes it made.
2026-04-16 01:54:09 -04:00
Jacob Pratt
2beaa602c4 Rollup merge of #154604 - CAD97:abort-immediate, r=scottmcm
abort in core

Implements `core::process::abort_immediate` as a wrapper around `intrinsics::abort`.

- tracking issue: https://github.com/rust-lang/rust/issues/154601

(This PR used to also add `core::process::abort`, but that's been deferred to a later addition.)
2026-04-16 01:54:09 -04:00
Jacob Pratt
c83f586c6e Rollup merge of #150649 - hkBst:non-canonical-clone-impl-1, r=scottmcm
clippy fix: non_canonical_clone_impl

Fixes:

```text
warning: non-canonical implementation of `clone` on a `Copy` type
   --> library/core/src/clone.rs:682:33
    |
682 |           fn clone(&self) -> Self {
    |  _________________________________^
683 | |             self
684 | |         }
    | |_________^ help: change this to: `{ *self }`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#non_canonical_clone_impl
    = note: requested on the command line with `-W clippy::non-canonical-clone-impl`

warning: non-canonical implementation of `clone` on a `Copy` type
   --> library/core/src/convert/mod.rs:935:35
    |
935 |       fn clone(&self) -> Infallible {
    |  ___________________________________^
936 | |         match *self {}
937 | |     }
    | |_____^ help: change this to: `{ *self }`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#non_canonical_clone_impl

warning: non-canonical implementation of `clone` on a `Copy` type
   --> library/core/src/marker.rs:856:29
    |
856 |       fn clone(&self) -> Self {
    |  _____________________________^
857 | |         Self
858 | |     }
    | |_____^ help: change this to: `{ *self }`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#non_canonical_clone_impl

```
2026-04-16 01:54:08 -04:00
Jacob Pratt
a25356babb Rollup merge of #155357 - Urgau:rustdoc-remap-path-scope, r=GuillaumeGomez
Add `--remap-path-scope` as unstable in rustdoc

This PR adds support for `rustc` `--remap-path-scope` flag in rustdoc as unstable.

`rustc` documentation for the flag is [here](https://doc.rust-lang.org/nightly/rustc/remap-source-paths.html#--remap-path-scope).

I added some complementary tests for `rustdoc`, no need I think to duplicate `rustc` UI tests.
2026-04-16 01:54:07 -04:00
Jacob Pratt
700f2a7967 Rollup merge of #155353 - petrochenkov:globdedup, r=mu001999
resolve: Remove `inaccessible_ctor_reexport` resolver field

Collect the necessary information during error reporting instead of doing it on a good path from the core name resolution infra.

Also cleanup the related diagnostic code for struct constructors in general, see the individual commits.

This mitigates most of the harm brought by https://github.com/rust-lang/rust/pull/133477.
2026-04-16 01:54:07 -04:00
Jacob Pratt
1c9abe206b Rollup merge of #154699 - Jules-Bertholet:lt-for-cased, r=scottmcm
`core::unicode`: Replace `Cased` table with `Lt`

Shaves off 368 bytes from the total size of all Unicode data tables.

@rustbot label A-unicode
2026-04-16 01:54:06 -04:00
Jacob Pratt
0238243b5f Rollup merge of #154599 - folkertdev:varargs-without-pattern-in-deps, r=mati865
report the `varargs_without_pattern` lint in deps

tracking issue: https://github.com/rust-lang/rust/issues/44930

After discussion in https://github.com/rust-lang/reference/pull/2177#discussion_r2864885208.

Based on https://github.com/rust-lang/rust/pull/143619#issuecomment-3133157725 there was only one actual impacted crate https://crates.io/crates/binrw. The issue was fixed in https://github.com/jam1garner/binrw/issues/342, and has since been released https://github.com/jam1garner/binrw/issues/342#issuecomment-3994700268.

Hence we may as well report this loudly.

r? @ghost
2026-04-16 01:54:05 -04:00
Jacob Pratt
402748551a Rollup merge of #154595 - mu001999-contrib:fix/154539, r=BoxyUwU
Emit fatal on invalid const args with nested defs

Fixed https://github.com/rust-lang/rust/issues/123629
Fixes https://github.com/rust-lang/rust/issues/154539

Invalid const args are rejected, so their surrounding HIR is not preserved. But nested defs inside them can still get created, leaving children lowered without a valid HIR parent and causing an ICE when later error handling walks HIR parents.

r? @BoxyUwU
2026-04-16 01:54:05 -04:00
Jacob Pratt
89cca04b5f Rollup merge of #154451 - scottmcm:require-residual, r=jhpratt
Require that a `<_ as Try>::Residual` implement the `Residual` trait

The `Residual` trait was even more experimental than `Try`, but now that https://github.com/rust-lang/rfcs/pull/3721 is merged, I think it would make sense to require this.  Technically it's not strictly required, but without it something working on `<T: Try>` might need an extra bound even to use a homogeneous try block with the same output type as `T::Output`.  (Another `where` will of course be needed to return a *different* `impl Try` type still.)

cc https://github.com/rust-lang/rust/issues/154391
2026-04-16 01:54:04 -04:00
The rustc-josh-sync Cronjob Bot
cf1af01dd8 Merge ref 'e8e4541ff196' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@e8e4541ff1
Filtered ref: rust-lang/rust-analyzer@77fb39b687
Upstream diff: 4c4205163a...e8e4541ff1

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-16 05:14:09 +00:00
The rustc-josh-sync Cronjob Bot
202df42f86 Prepare for merging from rust-lang/rust
This updates the rust-version file to e8e4541ff1.
2026-04-16 05:08:47 +00:00
A4-Tacks
96d23277cf Merge pull request #22057 from Shourya742/2026-04-16-remove-clone-for-update
Remove clone_for_update in move_const_to_impl
2026-04-16 04:41:52 +00:00
Martin Nordholts
98242676d9 tests/debuginfo/basic-stepping.rs: Remove FIXME related to ZSTs
We don't consider it a bug that users can't break on initialization of
some non-zero sized types (see comment on `maximally-steppable` at the
top of the file), so it does not make sense to consider it a bug that
users can't break on initialization of some zero-sized types.
2026-04-16 06:05:12 +02:00
bit-aloo
574a1982e5 remove clone_for_update in move_const_to_impl 2026-04-16 09:26:23 +05:30
bit-aloo
84d65db7a6 adapt raw strings to new SyntaxEditor semantics 2026-04-16 09:21:33 +05:30
bit-aloo
3083d7996f replace make with syntaxFactory 2026-04-16 09:16:10 +05:30
Jules Bertholet
a9d7027f39 rustdoc: percent-encode URL fragments 2026-04-15 22:32:07 -04:00
Naveen Iyer
46f360abbd Add regression test for dead code elimination with drop + panic
Dead code elimination used to fail when a Drop impl contained a panic
and a potentially-panicking external function was called after the value
was created. This was fixed since 1.82 but no regression test was added.

The test verifies that foo() compiles to just a call to unknown() and
ret void, with no panic or panicking call in the function body.

Signed-off-by: Naveen R. Iyer <iyernaveenr@gmail.com>
2026-04-16 01:48:00 +00:00
Jason Newcomb
5ba0e3a6b4 Parenthesize AssocOp::Cast in suggestion when replacement operator is < to avoid parse error (#16848)
Fix int_plus_one suggestion causing parse error when LHS is an
`AssocOp::Cast`

When int_plus_one rewrites an expression like `x as usize + 1 <= y`, it
  suggests `x as usize < y`. This doesn't compile because the parser
  interprets `usize<y>` as the start of generic arguments rather than a
  lt comparison.

The fix parenthesizes the LHS if it's an `AssocOp::Cast` and the
replacement
  operator is `<`: `(x as usize) < y`.

  ---
changelog: [int_plus_one]: Parenthesize `AssocOp::Cast` in suggestion
when replacement operator is < to avoid parse error
2026-04-16 01:17:26 +00:00
Scott McMurray
3efcdbc43c Require that a <_ as Try>::Residual implement Residual
The `Residual` trait was even more experimental than `Try`, but now that RFC3721 is merged, I think it would make sense to require this.
2026-04-15 18:09:52 -07:00
Nicholas Nethercote
f3fc5376e8 Move MustBeNameOfAssociatedFunction to the crate that uses it. 2026-04-16 08:56:50 +10:00
Nicholas Nethercote
9b64d52d78 Reduce diagnostic type visibilities.
Most diagnostic types are only used within their own crate, and so have
a `pub(crate)` visibility. We have some diagnostic types that are
unnecessarily `pub`. This is bad because (a) information hiding, and (b)
if a `pub(crate)` type becomes unused the compiler will warn but it
won't warn for a `pub` type.

This commit eliminates unnecessary `pub` visibilities for some
diagnostic types, and also some related things due to knock-on effects.
(I found these types with some ad hoc use of `grep`.)
2026-04-16 07:42:17 +10:00
teor
dafb6bb801 Refactor FnDecl and FnSig flags into packed structs 2026-04-16 07:08:08 +10:00
teor
0a742de04f Format missed clippy lint source files 2026-04-16 07:08:08 +10:00
teor
88adf7772d Fix typos near the refactor 2026-04-16 07:08:07 +10:00
niacdoial
3b123ce48e ImproperCTypes: Move erasing_region_normalisation into helper function
Another interal change that shouldn't impact rustc users.
To prepare for the upcoming split of visit_type, we reorganise the instances
of `cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty).unwrap_or(ty)`
into a helper function outside of the main structs.
2026-04-15 22:59:38 +02:00
Urgau
ae6dbdd9f0 Add --remap-path-scope as unstable in rustdoc 2026-04-15 21:26:48 +02:00
dependabot[bot]
e933b8d123 Bump thin-vec from 0.2.14 to 0.2.16
Bumps [thin-vec](https://github.com/mozilla/thin-vec) from 0.2.14 to 0.2.16.
- [Changelog](https://github.com/mozilla/thin-vec/blob/main/RELEASES.md)
- [Commits](https://github.com/mozilla/thin-vec/compare/v0.2.14...v0.2.16)

---
updated-dependencies:
- dependency-name: thin-vec
  dependency-version: 0.2.16
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-15 19:26:41 +00:00
WilliamTakeshi
dbb83b65b0 remove calls to AliasTyKind::def_id 2026-04-15 21:23:02 +02:00
Jonathan Brouwer
6236ddec5a Remove AttributeSafety from BUILTIN_ATTRIBUTES 2026-04-15 21:22:21 +02:00
Chayim Refael Friedman
9bf0d062c6 Merge pull request #22049 from Shourya742/2026-04-15-move-syntax-factory-inside-syntax-editor
Move syntax factory inside syntax editor
2026-04-15 19:09:18 +00:00
Vadim Petrochenkov
19c7df6f3f resolve: Remove inaccessible_ctor_reexport resolver field
Collect the necessary information during error reporting instead of doing it on a good path from the core name resolution infra
2026-04-15 21:49:10 +03:00
Vadim Petrochenkov
9c2e42418c resolve: Remove type Res aliases except the one in the crate root
Use imports instead
2026-04-15 21:49:10 +03:00
Vadim Petrochenkov
32381125bb resolve: Cleanup diagnostic code for struct constructors 2026-04-15 21:49:10 +03:00
bit-aloo
4445220800 Adapt changes to assist so that we no longer use mutable editor 2026-04-16 00:17:47 +05:30
bit-aloo
567d676388 introduce interior mutability to SyntaxEditor to let go of &mut usage 2026-04-16 00:04:49 +05:30
Martin Nordholts
f684713c43 triagebot.toml: Sync assign.owners with autolabel."T-compiler"
In `autolabel."T-compiler"`, several `./tests/*` dirs are listed.

But many of them are missing from `assign.owners`. Add them all to
`assign.owners` so reviewers are picked from the compiler group, and not
from the small `assign.adhoc_groups.fallback` group.
2026-04-15 20:33:24 +02:00
ujjwalVishwakarma2006
bcf86daada Add issue links 2026-04-15 23:50:36 +05:30
ujjwalVishwakarma2006
8c78c33aba Move test files from issues/ to appropriate subdirectories 2026-04-15 23:46:29 +05:30
bors
e8e4541ff1 Auto merge of #139087 - beetrees:impl-from-f16-for-f32, r=jackh726
Fallback `{float}` to `f32` when `f32: From<{float}>` and add `impl From<f16> for f32`



Currently, the following code compiles:
```rust
fn foo<T: Into<f32>>(_: T) {}

fn main() {
    foo(1.0);
}
```

This is because the only `From<{float}>` impl for `f32` is currently `From<f32>`. However, once `impl From<f16> for f32` is added this is no longer the case. This would cause the float literal to fallback to `f64`, subsequently causing a type error as `f32` does not implement `From<f64>`. While this kind of change to type inference isn't technically a breaking change according to Rust's breaking change policy, the previous attempt to add `impl From<f16> for f32` was removed rust-lang/rust#123830 due to the large number of crates affected (by my count, there were root regressions in 42 crates and 52 GitHub repos, not including duplicates). This PR solves this problem by using `f32` as the fallback type for `{float}` when there is a trait predicate of `f32: From<{float}>`. This allows adding `impl From<f16> for f32` without affecting the code that currently compiles (such as the example above; this PR shouldn't affect what is possible on stable).

This PR also allows adding a future-incompatibility warning for the fallback to `f32` (currently implemented in the third commit) if the lang team wants one (allowing the `f32` fallback to be removed in the future); alternatively this could be expanded in the future into something more general like @tgross35 suggested in https://github.com/rust-lang/rust/issues/123831#issuecomment-2064728053. I think it would be also possible to disallow the `f32` fallback in a future edition.

As expected, a crater check showed [no non-spurious regressions](https://github.com/rust-lang/rust/pull/139087#issuecomment-2764732580).

For reference, I've based the implementation loosely on the existing `calculate_diverging_fallback`. This first commit adds the `f32` fallback, the second adds `impl From<f16> for f32`, and the third adds a FCW lint for the `f32` fallback. I think this falls under the types team, so
r? types

Fixes: rust-lang/rust#123831
Tracking issue: rust-lang/rust#116909

@rustbot label +T-lang +T-types +T-libs-api +F-f16_and_f128

To decide on whether a future-incompatibility warning is desired or otherwise (see above):
@rustbot label +I-lang-nominated

cc https://github.com/rust-lang/rust/issues/154024 https://github.com/rust-lang/rust/issues/154005
2026-04-15 18:09:11 +00:00
Balt
d87a2e7ddd Fix typo for danging_ptr
Co-authored-by: Josh Stone <cuviper@gmail.com>
2026-04-15 11:56:45 -05:00
Balt
4095bbdd2d Add new Layout methods to release notes 2026-04-15 11:48:40 -05:00
Erick Tryzelaar
f52f12501b Add --quiet flag to x.py and bootstrap to suppress output
This adds a `--quiet` flag to x.py and bootstrap to suppress some of the
output when compiling Rust. It conflicts with `--verbose`, matching the
behavior of `cargo` which does not allow `--verbose` and `--quiet`.

It works by passing quiet flags down to the underlying cargo, or LLVM
build processes. Note that for LLVM, we only can suppress logs when we
explicitly configure it with ninja. Otherwise we won't know what flag
to pass along to whichever build system cmake decides to use.

This can be helpful with AI workloads in the Rust codebase to help
shrink down the output to reduce token usage, which can help prevent
context pollution and lower costs.

This patch was partially generated with Gemini, but I've reviewed the
changes it made.
2026-04-15 16:46:41 +00:00
Balt
fba9ef8702 Add insert_mut to release notes
Co-authored-by: Josh Stone <cuviper@gmail.com>
2026-04-15 11:38:59 -05:00
Balt
e910c38861 Add push_mut to release notes 2026-04-15 11:32:54 -05:00
Samuel Tardieu
c0adb72b3a Extend byte_char_slices to cover arrays (#16770)
Closes rust-lang/rust-clippy#16759

changelog: [`byte_char_slices`] enhance to cover arrays
2026-04-15 16:21:17 +00:00
linshuy2
d0c0f3a308 Enhance byte_char_slices to cover arrays 2026-04-15 18:16:03 +02:00
linshuy2
8d2de2185b Apply byte_char_slices to Clippy itself 2026-04-15 18:15:35 +02:00
Pavel Grigorenko
103923f250 single_use_lifetimes: respect anonymous_lifetime_in_impl_trait 2026-04-15 18:34:14 +03:00
bors
9620eae30a Auto merge of #155339 - JonathanBrouwer:rollup-2nyGW0a, r=JonathanBrouwer
Rollup of 5 pull requests

Successful merges:

 - rust-lang/rust#155331 (Reformat `top_level_options!` and `options!` macro declarations)
 - rust-lang/rust#155332 (bump std libc to `0.2.185`)
 - rust-lang/rust#155286 (attribute cleanup: rustc_confusables)
 - rust-lang/rust#155306 (`CValue::zst()` - add missing "ZST" in docs)
 - rust-lang/rust#155311 (various small `rustc_expand` cleanups)
2026-04-15 14:53:37 +00:00
Chayim Refael Friedman
491e8453b1 Merge pull request #22048 from ChayimFriedman2/upgrade-rustc
internal: Upgrade rustc crates
2026-04-15 14:07:49 +00:00
Chayim Refael Friedman
9a32199f92 Separate between normal evaluated consts and type-system consts
Type system consts (consts that participate in the type system, e.g. const generic params) have special properties: they must have strict equality independent of the user. For example, unions are not possible there. Therefore they are stored as a `ValTree`, a very simple representation that is good, mostly, for comparing things.

General consts can be anything (almost) - arbitrary bytes, even uninit bytes. They are stored like all consts previously were (in the type-system's `Const`), with bytes memory, in a new type called `Allocation` (named borrowed from rustc, although it isn't exactly accurate because in r-a it can represent multiple allocations).

The trigger for this change was a new requirement from rustc_type_ir, that type-system `Const` will be able to represent as a `ValTree`.
2026-04-15 16:57:38 +03:00
mu001999
77419b45dc Add FIXME for the fatal errors 2026-04-15 21:52:11 +08:00
Chayim Refael Friedman
982643abd9 Update solver types as required by the upgrade 2026-04-15 16:45:29 +03:00
Chayim Refael Friedman
c9440c593d Add support for scalable vectors repr
As it is now supported by rustc_abi.
2026-04-15 16:43:03 +03:00
Chayim Refael Friedman
ddc5e11770 Upgrade rustc crates 2026-04-15 16:43:03 +03:00
Lukas Wirth
722296ffd6 Merge pull request #22044 from ChayimFriedman2/internal-features
feat: Do not complete unstable items that use an internal feature
2026-04-15 13:42:25 +00:00
mu001999
1fca34d15d Emit fatal on defaults for generic params in binders if with nested defs 2026-04-15 21:41:19 +08:00
Lukas Wirth
53b20e4965 Merge pull request #22032 from ChayimFriedman2/assoc-types-yet-again
fix: Allow ambiguity in assoc type shorthand if they resolve to the same assoc type, between supertraits this time
2026-04-15 13:39:11 +00:00
Lukas Wirth
99ec949f5e Merge pull request #22046 from yPin9/2026-04-15-parse-type-const
parse `type const` items
2026-04-15 13:38:39 +00:00
Chayim Refael Friedman
067f4c6ce2 Merge pull request #22050 from ChayimFriedman2/make-asyncs-closures
internal: Represent lowered coroutines with closures
2026-04-15 13:15:08 +00:00
Chayim Refael Friedman
6f703399c9 Represent lowered coroutines with closures
This is how rustc does it, because they're similar in many ways, and most importantly: they share (or will share, not yet) capture analysis.

Also:
 - Copy closure inference from rustc again, this time really precisely.
 - Have separate ID types for coroutine closures and normal closures, for better type safety.
 - Validate, when constructing interned closures/coroutines/coroutine closures and `cfg(debug_assertions)`, that the `ExprId` is of an expr of the correct kind.
2026-04-15 16:05:03 +03:00
Amanieu d'Antras
9e4d2a7ca8 Merge pull request #2071 from davidtwco/sve-intrinsics
initial SVE intrinsics
2026-04-15 12:47:10 +00:00
Jonathan Brouwer
439410f68a Rollup merge of #155311 - cyrgani:expand-clean, r=Kivooeo,petrochenkov
various small `rustc_expand` cleanups

Each commit should be reviewable on its own.
2026-04-15 14:39:09 +02:00
Jonathan Brouwer
420eec616f Rollup merge of #155306 - DanielEScherzer:cvalue-zst-article, r=JohnTitor
`CValue::zst()` - add missing "ZST" in docs
2026-04-15 14:39:08 +02:00
Jonathan Brouwer
1de718c323 Rollup merge of #155286 - mejrs:confusables, r=JonathanBrouwer
attribute cleanup: rustc_confusables

r? @jdonszelmann
2026-04-15 14:39:07 +02:00
Jonathan Brouwer
86fe9e259d Rollup merge of #155332 - folkertdev:bump-std-libc-0.2.185, r=tgross35
bump std libc to `0.2.185`

https://github.com/rust-lang/libc/releases/tag/0.2.185

r? tgross35
2026-04-15 14:39:06 +02:00
Jonathan Brouwer
e4eff63647 Rollup merge of #155331 - Zalathar:options-fmt, r=petrochenkov
Reformat `top_level_options!` and `options!` macro declarations

These macros are already tricky, and having weird formatting doesn't help. Using a more regular style makes it easier to see where nesting begins and ends.

Extracted from https://github.com/rust-lang/rust/pull/154501 after the changes in https://github.com/rust-lang/rust/pull/149357 made rebasing very difficult.

There should be no change to compiler behaviour.
2026-04-15 14:39:06 +02:00
Oli Scherer
8d642647bd Handle non-null pattern types in size skeleton 2026-04-15 14:37:41 +02:00
zvkemp
69958674d5 conditionally wrap LHS of int_plus_one error to avoid parser ambiguity 2026-04-15 08:35:42 -04:00
Oli Scherer
82545d7d79 Add regression test 2026-04-15 14:24:11 +02:00
mejrs
d6bccac835 Fix error code example 2026-04-15 13:50:43 +02:00
dependabot[bot]
02fa156965 Bump follow-redirects from 1.15.9 to 1.16.0 in /editors/code
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.15.9 to 1.16.0.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.15.9...v1.16.0)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-version: 1.16.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-15 11:10:18 +00:00
bors
32e4c0ecbd Auto merge of #155256 - cuviper:hashbrown-0.17, r=Mark-Simulacrum
compiler: update hashbrown to 0.17

See library's rust-lang/rust#155154 for the bug fixes this brings.
This PR also updates `indexmap` in the compiler as a direct dependent.
2026-04-15 11:01:30 +00:00
Folkert de Vries
bbc45547f3 Merge pull request #2079 from eduardosm/mips-tests
Fix MIPS tests
2026-04-15 10:04:09 +00:00
Shun Sakai
81cab931a1 docs: Use 0b1 instead of NonZero::MIN in NonZero::bit_width doctests 2026-04-15 19:03:49 +09:00
Nicholas Nethercote
3ce3436fd6 Disallow ZST allocations with TypedArena.
`DroplessArena::alloc` already disallows ZST allocation.
`TypedArena::alloc` allows it but:
- (a) it's never used, and
- (b) writing to `NonNull::dangling()` seems dubious, even if the write
  is zero-sized.

This commit just changes it to panic on a ZST. This eliminates an
untested code path, and we shouldn't be allocating ZSTs anyway.
It also eliminates an unused ZST code path in `clear_last_chunk`.
Tests are also updated accordingly.
2026-04-15 20:03:07 +10:00
Folkert de Vries
2fe569d25f bump std libc to 0.2.185 2026-04-15 11:56:20 +02:00
mejrs
1d6177020c Add test for coalescing of diagnostic attribute duplicates 2026-04-15 11:49:55 +02:00
Zalathar
4506131794 Reformat top_level_options! and options! macro declarations 2026-04-15 18:33:48 +10:00
nataliakokoromyti
7d680171f0 borrowck: suggest borrowing for destructuring moves from overloaded deref 2026-04-15 00:59:25 -07:00
bit-aloo
15b3b408fd Remove all occurance of explicit SyntaxFactory::with_mapping, and update all the occurances to use make via SyntaxEditor 2026-04-15 12:16:30 +05:30
bit-aloo
a6f0e7872a fix constructor mapping which were incorrect 2026-04-15 12:13:45 +05:30
bit-aloo
6615cd9679 move SyntaxFactory inside SyntaxEditor 2026-04-15 12:12:31 +05:30
bors
57cb10ae1e Auto merge of #155324 - jhpratt:rollup-BNB8Pcb, r=jhpratt
Rollup of 13 pull requests

Successful merges:

 - rust-lang/rust#154882 (Gate tuple const params behind `min_adt_const_params` feature)
 - rust-lang/rust#155259 (explicit-tail-calls: disable two tests on LoongArch)
 - rust-lang/rust#155293 (fix arch names in cfg pretty printer)
 - rust-lang/rust#155314 (`BorrowedBuf`: Update outdated safety comments in `set_init` users.)
 - rust-lang/rust#153469 (docs: clarify path search behavior in std::process::Command::new)
 - rust-lang/rust#154765 (Clarify ascii whitespace exclusion of vertical tab in the doc)
 - rust-lang/rust#155172 (Some small nits for supertrait_item_shadowing, and additional testing)
 - rust-lang/rust#155279 (Test/lexer unicode pattern white space)
 - rust-lang/rust#155280 (Tests for precise-capture through RPIT and TAIT)
 - rust-lang/rust#155301 (Delete unused `rustc_trait_selection` errors.)
 - rust-lang/rust#155303 (remove ibraheemdev from review rotation)
 - rust-lang/rust#155304 (remove PointeeParser)
 - rust-lang/rust#155319 (Remove dead diagnostic structs.)
2026-04-15 05:15:32 +00:00
lms0806
be3f77c7ff resolve : addressing incorrect recommendation methods 2026-04-15 13:23:37 +09:00
lms0806
96fb37ae60 add : new UI test 2026-04-15 13:23:23 +09:00
Jacob Pratt
aeaa84995e Rollup merge of #155319 - nnethercote:rm-dead-error-structs, r=Kivooeo
Remove dead diagnostic structs.

One of these has a "FIXME(autodiff): I should get used somewhere" comment, but I figure YAGNI applies and it's so small that reinstating it if necessary would be trivial.

r? @Kivooeo
2026-04-14 23:02:37 -04:00
Jacob Pratt
e20fc9c303 Rollup merge of #155304 - Bryntet:remove-pointee-parser, r=JonathanBrouwer
remove PointeeParser

this parser does nothing currently, as the current scope of `rustc_attr_parsing` only includes builtin attributes, and not derive macros

it isn't defined in `compiler/rustc_feature/src/builtin_attrs.rs`

all the actual parsing for `#[pointee]` is actually handled in `compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs`

r? @JonathanBrouwer
2026-04-14 23:02:37 -04:00
Jacob Pratt
edeacddbc7 Rollup merge of #155303 - WaffleLapkin:ibraheemdev, r=tgross35
remove ibraheemdev from review rotation

@ibraheemdev haven't reviewed any r-l/r PRs since October last year and has a backlog of [8 PRs at the moment of writing this](https://github.com/rust-lang/rust/pulls?q=is%3Aopen+is%3Apr+assignee%3Aibraheemdev+label%3AS-waiting-on-review).

@ibraheemdev thank you for the reviews that you have done in the past! feel free to re-add yourself once you have time for this again :)
2026-04-14 23:02:36 -04:00
Jacob Pratt
3002472a77 Rollup merge of #155301 - mejrs:dead, r=nnethercote
Delete unused `rustc_trait_selection` errors.

The first two of these are duplicated elsewhere in some form or another, apparently they became orphaned during various moves and refactors. The third is just never used.
2026-04-14 23:02:35 -04:00
Jacob Pratt
900e3a7720 Rollup merge of #155280 - Zalathar:opaque-capture-bug, r=JonathanBrouwer
Tests for precise-capture through RPIT and TAIT

- Tests for https://github.com/rust-lang/rust/issues/155151.

These tests succeed under `-Znext-solver`, but incorrectly fail under the old trait solver.

---

The bug can be triggered via return-position `impl Trait` on stable, but requires some rather contrived code. When using type-alias `impl Trait`, it's easier to imagine the issue being triggered by real code.
2026-04-14 23:02:35 -04:00
Jacob Pratt
07f5dcaac7 Rollup merge of #155279 - Sandijigs:test/lexer-unicode-pattern-white-space, r=jdonszelmann
Test/lexer unicode pattern white space

This PR adds a test for the Rust lexer to verify it correctly accepts vertical tab (`\x0B`) as valid whitespace between tokens. Vertical tab is part of Unicode Pattern_White_Space, which the Rust language specification uses to define whitespace.

Related: Outreachy tracking [Pattern_White_Space](https://www.unicode.org/reports/tr31/#R3a)
2026-04-14 23:02:34 -04:00
Jacob Pratt
5cff48a164 Rollup merge of #155172 - jackh726:supertrait-shadowing-cleanup, r=lcnr
Some small nits for supertrait_item_shadowing, and additional testing

cc rust-lang/rust#89151

r? types
2026-04-14 23:02:33 -04:00
Jacob Pratt
78a1300310 Rollup merge of #154765 - krtab:doc_ascii_whitespace, r=Mark-Simulacrum,WaffleLapkin
Clarify ascii whitespace exclusion of vertical tab in the doc

This especially means that for `c: char`, `c.is_ascii() && c.is_whitespace()` does **not** imply `c.is_ascii_whitespace()`, which can cause bug and is highly counterintuitive.
2026-04-14 23:02:33 -04:00
Jacob Pratt
3f19aa5672 Rollup merge of #153469 - Albab-Hasan:doc/command-path-search-behavior, r=ChrisDenton
docs: clarify path search behavior in std::process::Command::new

the existing docs mentioned that `PATH` is searched in an "os defined way" and that it could be controlled by setting PATH on the command but never explained which `PATH` is actually used.

on unix the key thing to understand is that when you modify the childs environment (via `env()`, `env_remove()`, or `env_clear()`), the `PATH` search uses whatever `PATH` ends up in the child's environment not the parents. so if you call `env_clear()` and forget to set `PATH`, you don't get the parents `PATH` as a fallback; you get the OS default (typically `/bin:/usr/bin`) which often won't find what you need.

the three cases are now documented:
- unmodified env: child inherits parents `PATH`, that gets searched
- `PATH` explicitly set `via env()`: the new value is searched
- `PATH` removed (`env_clear` or `env_remove`): falls back to OS default, not the parents `PATH`

on windows rust resolves the executable before spawning rather than letting `CreateProcessW` do it. the search order is: childs `PATH` (if explicitly set) first then system-defined directories then the parents `PATH`. the existing note about issue rust-lang/rust#37519 is preserved.

limitations in this doc:
- the unix fallback path behavior ("typically `/bin:/usr/bin`") is verified for linux/glibc. behavior on macOS, BSD, and musl is similar in practice but not fully confirmed here.
- the windows search order is summarized as "system-defined directories" which actually includes the application directory (the directory of the calling process's executable) as a distinct step before the system dirs that detail is omitted for brevity.
- `posix_spawnp` `PATH` source (calling process environ vs envp argument) is ambiguous in the `POSIX` spec; the behavior here is inferred from the guard in `unix.rs` that bypasses `posix_spawn` when `PATH` has been modified.

closes rust-lang/rust#137286 (hopefully)
2026-04-14 23:02:32 -04:00
Jacob Pratt
85c11f656b Rollup merge of #155314 - briansmith:b/comments, r=joshtriplett
`BorrowedBuf`: Update outdated safety comments in `set_init` users.

These comments appear to have been written before `BorrowedBuf`'s init tracking was simplified in
https://github.com/rust-lang/rust/pull/150129. The `BufWriter` comment of the usage within `BufWriter` will be handled separately.

CC rust-lang/rust#78485, rust-lang/rust#117693.
2026-04-14 23:02:31 -04:00
Jacob Pratt
48865507d0 Rollup merge of #155293 - usamoi:rustdoc-loongarch, r=GuillaumeGomez
fix arch names in cfg pretty printer

It's introduced in https://github.com/rust-lang/rust/pull/154328.

@rustbot label +beta-nominated

(it affects the documentation of [`core::arch::loongarch32`](https://doc.rust-lang.org/beta/core/arch/loongarch32/index.html) and [`core::arch::loongarch64`](https://doc.rust-lang.org/beta/core/arch/loongarch64/index.html))
2026-04-14 23:02:31 -04:00
Jacob Pratt
de84f87874 Rollup merge of #155259 - durin42:llvm-23-loongarch-tailcall, r=chenyukang
explicit-tail-calls: disable two tests on LoongArch

A [recent LLVM change](https://github.com/llvm/llvm-project/pull/191508) broke these on LLVM 23.

I suspect these will eventually be fixed, so maybe it'd be okay/better to just leave this pending so it applies to our CI without merging it? I'm open to opinions.
2026-04-14 23:02:30 -04:00
Jacob Pratt
c6363238fa Rollup merge of #154882 - zedddie:gate-tuple-const-params, r=BoxyUwU
Gate tuple const params behind `min_adt_const_params` feature

r? BoxyUwU
2026-04-14 23:02:30 -04:00
bors
bd1e7c7948 Auto merge of #153815 - GokhanKabar:fix-ice-enum-discr-generic-self, r=BoxyUwU
Fix ICE when Self is used in enum discriminant of a generic enum



Fixes rust-lang/rust#153756
Let discriminant AnonConst inherit parent generics via Node::Variant in generics_of, and emit a proper error instead of span_bug! for the TooGeneric case in wfcheck.
2026-04-15 01:58:56 +00:00
Esteban Küber
b849e10d38 Make span_suggestions always verbose
`span_suggestions` is to provide mutually exclusive suggestions. When it was introduced, we made its behavior be that if a single suggestion is given to it, we present the suggestion inline, otherwise in patch format. Changing this to make all of its uses be verbose, as that is closer in intent of output.
2026-04-15 01:38:14 +00:00
Nicholas Nethercote
f093767036 Remove dead diagnostic structs.
One of these has a "FIXME(autodiff): I should get used somewhere"
comment, but I figure YAGNI applies and it's so small that reinstating
it if necessary would be trivial.
2026-04-15 08:54:46 +10:00
mejrs
72db94ff17 Pass allowed options as parameter to diagnostic lints 2026-04-15 00:24:17 +02:00
Mark Rousskov
f0827c67ca Apply replace-version-placeholder 2026-04-14 18:09:15 -04:00
Brian Smith
10cff1530d BorrowedBuf: Update outdated safety comments in set_init users.
These comments appear to have been written before `BorrowedBuf`'s
init tracking was simplified in
https://github.com/rust-lang/rust/pull/150129. The `BufWriter` comment
of the usage within `BufWriter` will be handled separately.
2026-04-14 14:59:21 -07:00
mejrs
75273e21c9 Warn instead of error for some ructs_on_unimplemented errors 2026-04-14 23:37:13 +02:00
Folkert de Vries
a7590138a7 thread through a HirId to emit lints in the right place
Previously the lint would be reported at the right span, but could not be `allow`ed or `expect`ed in that location, because the lint was actually emitted using `CRATE_HIR_ID`
2026-04-14 23:21:54 +02:00
Ralf Jung
bae3b39081 Merge pull request #4955 from WhySoBad/network-socket-set-non-blocking
Allow changing socket blocking state
2026-04-14 21:00:01 +00:00
cyrgani
2e3036dc54 merge if and while conditions 2026-04-14 20:45:04 +00:00
WhySoBad
abc05d7b06 Allow changing socket blocking state
Add shims for `fcntl` and `ioctl` to change socket blocking mode.
2026-04-14 22:34:35 +02:00
Daniel Scherzer
bd712bd224 CValue::zst() - add missing "ZST" in docs 2026-04-14 13:22:50 -07:00
cyrgani
3dcd8ffe88 deduplicate internal feature check 2026-04-14 19:58:15 +00:00
cyrgani
6e458a5fca simplify make_stmts_default! 2026-04-14 19:48:17 +00:00
Ralf Jung
b2ffd38ae2 Merge pull request #4961 from RalfJung/genmc-tests
genmc tests: add -Zmiri-genmc by default
2026-04-14 18:44:27 +00:00
John Kåre Alsaker
99ed1b81d7 Make convert_while_ascii unsafe 2026-04-14 20:27:30 +02:00
Edvin Bryntesson
2598b50f92 remove PointeeParser 2026-04-14 20:25:43 +02:00
Waffle Lapkin
0a0dc9e13c remove ibraheemdev from review rotation 2026-04-14 20:03:24 +02:00
Eduardo Sánchez Muñoz
69aad1af38 Fix MIPS tests
Tests failed to build due to use of legacy const generics syntax, out-of-bounds immediates and incorrect name of const generics in `assert_instr`
2026-04-14 19:55:48 +02:00
Albab Hasan
a34d15f423 Update library/std/src/process.rs
Co-authored-by: Chris Denton <chris@chrisdenton.dev>
2026-04-14 23:39:04 +06:00
mejrs
c8c4f02d00 Delete unused rustc_trait_selection errors. 2026-04-14 19:33:36 +02:00
albab-hasan
97761a0c23 docs: move PATH search details under Platform-specific behavior, add stability
caveat
2026-04-14 23:02:47 +06:00
dswij
effe235710 Fix expect_fun_call suggests wrongly for string slicing (#16752)
Closes rust-lang/rust-clippy#16747

changelog: [`expect_fun_call`] fix wrong suggestions for string slicing
2026-04-14 16:59:51 +00:00
Folkert de Vries
dfb680751e mark From<f16> for f32 as an unstable instance 2026-04-14 18:51:24 +02:00
beetrees
7aad5c0784 Add FCW for unsuffixed float literal f32 fallback 2026-04-14 18:38:01 +02:00
beetrees
f354fa86b3 Add impl From<f16> for f32 2026-04-14 18:38:01 +02:00
beetrees
c021d2ddd4 Fallback {float} to f32 when f32: From<{float}> 2026-04-14 18:38:00 +02:00
cijiugechu
28b0ef6683 Add FIXME 2026-04-15 00:29:50 +08:00
ypp
e95ac9eb1f parse type const items
Adds parser support for the unstable `type const` syntax from the
`min_generic_const_args` feature, e.g. `type const FOO: i32 = 2;`.

Closes rust-lang/rust-analyzer#22038.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 00:18:51 +08:00
Elichai Turkel
bb9788bd42 Add _mm512_permutexvar_epi64 shim 2026-04-14 19:17:37 +03:00
bors
a5c825cd82 Auto merge of #155292 - JonathanBrouwer:rollup-AJQWqfn, r=JonathanBrouwer
Rollup of 7 pull requests

Successful merges:

 - rust-lang/rust#154049 (delegation: Track more precise spans for glob delegations)
 - rust-lang/rust#155134 (Replace custom trim_ascii_start with the standard library method)
 - rust-lang/rust#155235 (add the `fma4` x86 target feature)
 - rust-lang/rust#155218 (coroutines: Skip the closure signature annotation check for tainted bodies)
 - rust-lang/rust#155274 (limit duplicate-profiler-builtins test to targets that can do dynamic linking)
 - rust-lang/rust#155276 (`#[rustc_must_match_exhaustively]` detect let else)
 - rust-lang/rust#155281 (Revert "allow `windows-gnu` targets to embed gdb visualizer scripts")
2026-04-14 15:41:02 +00:00
usamoi
05081b96c9 fix arch names in cfg pretty printer 2026-04-14 23:38:25 +08:00
lapla
b17a3e2f2d Fix misleading "borrowed data escapes outside of function" diagnostic 2026-04-15 00:35:52 +09:00
Ralf Jung
3896b15aba genmc tests: add -Zmiri-genmc by default 2026-04-14 17:03:15 +02:00
GokhanKabar
aacac7e2e3 Fix ICE when Self is used in enum discriminant of a generic enum
* Fix ICE when Self is used in enum discriminant of a generic enum

Move the validation into the existing `check_param_uses_if_mcg` machinery
in HIR ty lowering instead of adding a new check in wfcheck. After the
`AnonConstKind` refactoring, `ForbidMCGParamUsesFolder` was only gated on
`AnonConstKind::MCG`, causing discriminant anon consts (`NonTypeSystem`) to
bypass it entirely.

Add `anon_const_forbids_generic_params()` which returns the appropriate
`ForbidParamContext` for both MCG and enum discriminant contexts. Wire it
into `check_param_uses_if_mcg` so that `Self` aliasing a generic type is
caught before reaching `const_eval_poly`. Convert the `TooGeneric` span_bug
into a proper diagnostic as a fallback for anything slipping through
type-dependent path resolution.
* Address review comments

- Rename `ForbidMCGParamUsesFolder` to `ForbidParamUsesFolder`
- Rename `MinConstGenerics` variant to `ConstArgument` with updated doc
- Simplify doc comment on `anon_const_forbids_generic_params`
- Make match on `AnonConstKind` exhaustive
- Move `anon_const_def_id` inside the `if let` in `check_param_uses_if_mcg`
- Remove now-unreachable `TooGeneric` span_err in wfcheck
* Revert TooGeneric arm back to span_bug! as requested by reviewer
* Use generics_of to determine if NonTypeSystem anon consts allow generic params
* Also check InlineConst and Closure defs nested in enum discriminants
* Simplify logic for determining anonymous constant parent in generic contexts
* add test
2026-04-14 14:32:11 +00:00
Jonathan Brouwer
2d27fe6a5e Rollup merge of #155281 - folkertdev:revert-154840, r=folkertdev
Revert "allow `windows-gnu` targets to embed gdb visualizer scripts"

Fixes https://github.com/rust-lang/rust/issues/155277

This reverts commit 472b966548.

This was merged as https://github.com/rust-lang/rust/pull/154840, but causes linker errors in the wild.

cc @Walnut356 @mati865
r? @ghost
2026-04-14 16:29:37 +02:00
Jonathan Brouwer
960a56fc4c Rollup merge of #155276 - jdonszelmann:must-match-exhaustively-let-else, r=JonathanBrouwer
`#[rustc_must_match_exhaustively]` detect let else

Extension of https://github.com/rust-lang/rust/pull/155047, I forgor to lint on let-else :3
2026-04-14 16:29:36 +02:00
Jonathan Brouwer
10e6d6c7d9 Rollup merge of #155274 - tshepang:patch-1, r=lqd
limit duplicate-profiler-builtins test to targets that can do dynamic linking

this is the error I got for an example of such a target
```
=== STDERR ===
error: extern location for dylib_a does not exist: libdylib_a.so
 --> main.rs:2:5
  |
2 |     dylib_a::something();
  |     ^^^^^^^

error: extern location for dylib_b does not exist: libdylib_b.so
 --> main.rs:3:5
  |
3 |     dylib_b::something_else();
  |     ^^^^^^^
2026-04-14 16:29:35 +02:00
Jonathan Brouwer
aed02c58fc Rollup merge of #155218 - jakubadamw:issue-139570, r=tiif
coroutines: Skip the closure signature annotation check for tainted bodies

When a coroutine has too many parameters, `check_match` fails and `construct_error` builds a MIR body with only the coroutine's computed arguments (env + resume type). The user-provided signature, however, still reflects all the parameters the user wrote. `check_signature_annotation` then tries to `zip_eq` these two mismatched iterators, causing a panic. Checking `tainted_by_errors` and bailing early avoids this, since `construct_error` bodies cannot meaningfully be compared against user annotations.

Example currently ICEing:

```rust
fn main() {
    |(1, 42), ()| yield;
}
```

Closes rust-lang/rust#139570.
2026-04-14 16:29:34 +02:00
Jonathan Brouwer
b7286260c8 Rollup merge of #155235 - folkertdev:fma4-target-feature, r=sayantn
add the `fma4` x86 target feature

tracking issue: https://github.com/rust-lang/rust/issues/155233

Implications are based on LLVM

df6c82053c/llvm/lib/Target/X86/X86.td (L201-L206)

This feature adds a slightly better instruction encoding for fma. We might want to expose the intrinsics in `stdarch` with that target feature, but just adding the target feature in user code should already take advantage of this improved encoding.

This target feature is used in `libm`.

r? sayantn
2026-04-14 16:29:33 +02:00
Jonathan Brouwer
5da0b6cf1c Rollup merge of #155134 - thebabalola:fix/replace-trim-ascii-start-with-stdlib, r=mati865
Replace custom trim_ascii_start with the standard library method

The markdown parser in `rustc_errors` has a local `trim_ascii_start` function that strips leading ASCII whitespace from a byte slice. The standard library has had `<[u8]>::trim_ascii_start()` since Rust 1.80, which does the same thing.

This PR removes the custom function and calls the stdlib method directly in `parse_unordered_li` and `parse_ordered_li`. No behaviour change.

I also added a test covering the list item leading-whitespace trimming behaviour, including a tab case.

Fixes rustfoundation/interop-initiative#53
2026-04-14 16:29:32 +02:00
Jonathan Brouwer
49da27c336 Rollup merge of #154049 - petrochenkov:deleglobspan, r=jackh726
delegation: Track more precise spans for glob delegations

The last commit also fixes a macro hygiene issue with `self` in delegations found in https://github.com/rust-lang/rust/pull/154002.
2026-04-14 16:29:31 +02:00
Chayim Refael Friedman
3347cb8b4c Do not complete unstable items that use an internal feature
Unless the feature is enabled (and we're on nightly).

We can choose to not complete any unstable item if its feature is not enabled. However people may first type the thing then insert the feature. Only doing that for internal features is a good middle ground: normal people don't want their completion list polluted by `std::intrinsics` (even if they use nightly), and std people still get their completion if the feature is enabled (and realistically, it will be).
2026-04-14 17:23:42 +03:00
Chayim Refael Friedman
41b0052872 Merge pull request #22042 from Shourya742/2026-04-14-replace-make-with-syntaxFactory
Replace make with syntax factory in expand_glob_import
2026-04-14 13:33:26 +00:00
bit-aloo
7a56ebd961 replace make with syntax_factory definitions 2026-04-14 18:53:16 +05:30
bit-aloo
862febff7b add use tree list method to syntaxFactory constructor 2026-04-14 18:52:42 +05:30
Chayim Refael Friedman
6d6b7d0e8c Merge pull request #22036 from Shourya742/2026-04-14-remove-set-path
Replace set path usage with set_path_with_editor
2026-04-14 13:20:26 +00:00
Chayim Refael Friedman
15e4438c8b Merge pull request #21487 from A4-Tacks/extract-var-in-macro
feat: Support extract variable in macro call
2026-04-14 13:12:24 +00:00
bit-aloo
e32773b39c rename set_path_with_editor to set_path 2026-04-14 18:38:36 +05:30
bit-aloo
9919b15988 migrate destructure_tuple_binding and convert_let_else_to_match to use set_pat_with_editor 2026-04-14 18:38:36 +05:30
bit-aloo
533f183e0f remove set_pat from edit_in_place and move set_pat_with_editor in edit 2026-04-14 18:38:35 +05:30
Chayim Refael Friedman
edc1212a78 Merge pull request #22037 from Shourya742/2026-04-14-remove-set-visibility
Remove set visibility method
2026-04-14 12:57:45 +00:00
Chayim Refael Friedman
0d2aff0f19 Merge pull request #22039 from Shourya742/2026-04-14-replace-make-with-syntaxFactory-in-generate-blanket-trait-impl
Replace make with syntax factory in generate blanket trait impl
2026-04-14 12:54:23 +00:00
Chayim Refael Friedman
e89525568c Merge pull request #22041 from Shourya742/2026-04-14-remove-generic-params-owner-edit
Remove generic params owner edit
2026-04-14 12:53:02 +00:00
mejrs
f17ca97749 attribute cleanup: rustc_confusables 2026-04-14 14:24:26 +02:00
Ralf Jung
4e4d268b63 net::tcp/udp: fix docs about how set_nonblocking is implemented 2026-04-14 13:56:42 +02:00
Samuel Tardieu
ded01180f7 Add MSRV check for manual_noop_waker (#16850)
Fixes rust-lang/rust-clippy#16849

changelog: [`manual_noop_waker`]: Add MSRV check
2026-04-14 11:44:53 +00:00
Folkert de Vries
17f5fa0dd4 Revert "allow windows-gnu targets to embed gdb visualizer scripts"
This reverts commit 472b966548.
2026-04-14 13:27:46 +02:00
cyrgani
f4780504cd add and use PanicMessage::into_string 2026-04-14 11:16:33 +00:00
cyrgani
a681f34d4b add helper for profiling calls 2026-04-14 11:16:33 +00:00
cyrgani
e972232f27 reduce unnecessary allocations a bit 2026-04-14 11:16:32 +00:00
cyrgani
3fa55e721a clippy fixes 2026-04-14 11:16:32 +00:00
Zalathar
15fd168ee0 Tests for precise-capture through RPIT and TAIT 2026-04-14 21:14:10 +10:00
Sandijigs
7d4b12b600 Add lexer test for vertical tab as Pattern_White_Space whitespace 2026-04-14 11:49:28 +01:00
A4-Tacks
f74767b8d2 Add some fixme comments 2026-04-14 18:34:50 +08:00
A4-Tacks
c6b54969ef Support extract variable in macro call
Implement based first and last token mappings

Example
---
```rust
macro_rules! foo {
    (= $($t:tt)*) => { $($t)* };
}

fn main() {
    let x = foo!(= $02 + 3$0 + 4);
}
```

**Before this PR**

Assist not applicable

**After this PR**

```rust
macro_rules! foo {
    (= $($t:tt)*) => { $($t)* };
}

fn main() {
    let $0var_name = 2+3;
    let x = foo!(= var_name + 4);
}
```
2026-04-14 18:06:42 +08:00
bit-aloo
b1034b0361 update derive_macro 2026-04-14 15:02:32 +05:30
bit-aloo
4958d7703c remove generic params owner edit trait 2026-04-14 14:56:56 +05:30
Jana Dönszelmann
26a0fdcdcd fixup let-else on typing mode in the compiler 2026-04-14 11:05:19 +02:00
Jana Dönszelmann
778d27441d also check let-else 2026-04-14 11:05:19 +02:00
bors
12f35ad39e Auto merge of #155209 - JonathanBrouwer:attr_cleanup2, r=jdonszelmann
Post-attribute ports cleanup pt. 1 (again)

This is a re-implementation of most (but not all) of https://github.com/rust-lang/rust/pull/154808

The code is the same as in that PR, other than a few changes, I'll leave comments where I changed things.
I did re-implement most of the commits rather than cherry-picking, so it's probably good to check the entire diff regardless

r? @jdonszelmann
2026-04-14 08:59:40 +00:00
bors
f4b9b8d4f7 Auto merge of #155209 - JonathanBrouwer:attr_cleanup2, r=jdonszelmann
Post-attribute ports cleanup pt. 1 (again)

This is a re-implementation of most (but not all) of https://github.com/rust-lang/rust/pull/154808

The code is the same as in that PR, other than a few changes, I'll leave comments where I changed things.
I did re-implement most of the commits rather than cherry-picking, so it's probably good to check the entire diff regardless

r? @jdonszelmann
2026-04-14 08:59:40 +00:00
Tshepang Mbambo
8619841f05 limit duplicate-profiler-builtins test to targets that can do dynamic linking 2026-04-14 10:57:46 +02:00
bit-aloo
6c84b2b178 migrate generate blanket trait impl from make to SyntaxFactory 2026-04-14 14:13:01 +05:30
bit-aloo
42c6a7b269 add type_bound_text in constructor 2026-04-14 14:11:53 +05:30
Vadim Petrochenkov
f001d789c8 Update some tests after rebase 2026-04-14 11:33:15 +03:00
Vadim Petrochenkov
166c499a47 delegation: Give declaration of self syntax context of the delegation body
Instead of the last segment of the delegation path.
`self` is something that introduced by the whole delegation item, not some specific part of it, and the last segment may need to have a different context for path resolution purposes.
2026-04-14 11:32:34 +03:00
Vadim Petrochenkov
8114c5dc2e expand: More precise location for glob delegation
The span location of the last segment in the desugared path is inherited from the star symbol's span
2026-04-14 11:32:34 +03:00
Vadim Petrochenkov
7114404a26 ast: Preserve the star symbol span in glob delegation items 2026-04-14 11:32:33 +03:00
bit-aloo
d5146d345e remove set visibility method of HasVisibility 2026-04-14 13:31:41 +05:30
Ralf Jung
4e84b77011 Merge pull request #4960 from rust-lang/dependabot/cargo/rand-0.9.3
build(deps): bump rand from 0.9.2 to 0.9.3
2026-04-14 05:57:09 +00:00
Mend Renovate
fd47f70790 chore(deps): update rust crate rand to v0.10.1 [security] 2026-04-14 01:19:53 -04:00
bors
7db0ab43a7 Auto merge of #155270 - jhpratt:rollup-Djg7HpJ, r=jhpratt
Rollup of 3 pull requests

Successful merges:

 - rust-lang/rust#152530 (Use the term struct-like variant instead of anonymous structs for data of struct-like enum variants)
 - rust-lang/rust#155005 (preserve SIMD element type information)
 - rust-lang/rust#155230 (Avoid linting `doc_cfg` as unused in rustc)
2026-04-14 04:56:46 +00:00
Jacob Pratt
ec3a6b407f Rollup merge of #155230 - TaKO8Ki:fix-unused-features-doc-cfg, r=Kivooeo
Avoid linting `doc_cfg` as unused in rustc

Fixes rust-lang/rust#154487

af80b0f2cd/src/librustdoc/passes/propagate_doc_cfg.rs (L19-L26)
2026-04-14 00:37:25 -04:00
Jacob Pratt
803a7227fb Rollup merge of #155005 - folkertdev:simd-element-type-llvm, r=nnethercote
preserve SIMD element type information

Preserve the SIMD element type and provide it to LLVM for better optimization.

This is relevant for AArch64 types like `int16x4x2_t`, see also https://github.com/llvm/llvm-project/issues/181514. Such types are defined like so:

```rust
#[repr(simd)]
struct int16x4_t([i16; 4]);

#[repr(C)]
struct int16x4x2_t(pub int16x4_t, pub int16x4_t);
```

Previously this would be translated to the opaque `[2 x <8 x i8>]`, with this PR it is instead `[2 x <4 x i16>]`. That change is not relevant for the ABI, but using the correct type prevents bitcasts that can (indeed, do) confuse the LLVM pattern matcher.

This change will make it possible to implement the deinterleaving loads on AArch64 in a portable way (without neon-specific intrinsics), which means that e.g. Miri or the cranelift backend can run them without additional support.

discussion at [#t-compiler > loss of vector element type information](https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/loss.20of.20vector.20element.20type.20information/with/584483611)
2026-04-14 00:37:24 -04:00
Jacob Pratt
47d991a1aa Rollup merge of #152530 - orzechow:struct_like_enum_variants_docs, r=ChrisDenton
Use the term struct-like variant instead of anonymous structs for data of struct-like enum variants

The current term in the docs `anonymous structs` seems to be outdated.
I'd suggest `struct-like data` or rephrasing the whole sentence to use `struct-like variant`.

The terminology used in the [Rust Book on enums](https://doc.rust-lang.org/stable/book/ch06-01-defining-an-enum.html#listing-6-2) is
> named fields, like a struct

The [Reference on enums](https://doc.rust-lang.org/stable/reference/items/enumerations.html#r-items.enum.constructor) uses
> struct-like enum variant

The term `anonymous struct` on the other hand is neither mentioned in the Rust book on [structs](https://doc.rust-lang.org/stable/book/ch05-01-defining-structs.html) or [enums](https://doc.rust-lang.org/stable/book/ch06-01-defining-an-enum.html#listing-6-2), nor the references on [structs](https://doc.rust-lang.org/stable/reference/items/structs.html) or [enums](https://doc.rust-lang.org/stable/reference/items/enumerations.html#r-items.enum.constructor).
2026-04-14 00:37:23 -04:00
mu001999
6f1d601ca5 Update test with revisions 2026-04-14 12:28:19 +08:00
David Wood
b0d91aa86c core_arch: disable ld/st tests on msvc
There seemed to be non-deterministic failures on MSVC that looked like
corruption of the FFR in CI. Until this can be investigated, to avoid any
spurious failures, these tests are disabled.
2026-04-14 04:05:10 +00:00
Chayim Refael Friedman
0f4f33b1d4 Allow ambiguity in assoc type shorthand if they resolve to the same assoc type, between supertraits this time 2026-04-14 07:00:36 +03:00
Chayim Refael Friedman
9d0eb3f9eb Merge pull request #22035 from ChayimFriedman2/hangy-test
minor: Ignore a hangy test
2026-04-14 03:48:13 +00:00
lapla
4c4c8c75a1 Add MSRV check for manual_noop_waker 2026-04-14 12:46:51 +09:00
dependabot[bot]
89abb12593 build(deps): bump rand from 0.9.2 to 0.9.3
Bumps [rand](https://github.com/rust-random/rand) from 0.9.2 to 0.9.3.
- [Release notes](https://github.com/rust-random/rand/releases)
- [Changelog](https://github.com/rust-random/rand/blob/0.9.3/CHANGELOG.md)
- [Commits](https://github.com/rust-random/rand/compare/rand_core-0.9.2...0.9.3)

---
updated-dependencies:
- dependency-name: rand
  dependency-version: 0.9.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-14 03:38:00 +00:00
Chayim Refael Friedman
69716009f7 Ignore a hangy test 2026-04-14 06:37:50 +03:00
dependabot[bot]
c0d6de70ab build(deps): bump rand from 0.9.2 to 0.9.3
Bumps [rand](https://github.com/rust-random/rand) from 0.9.2 to 0.9.3.
- [Release notes](https://github.com/rust-random/rand/releases)
- [Changelog](https://github.com/rust-random/rand/blob/0.9.3/CHANGELOG.md)
- [Commits](https://github.com/rust-random/rand/compare/rand_core-0.9.2...0.9.3)

---
updated-dependencies:
- dependency-name: rand
  dependency-version: 0.9.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-14 03:19:41 +00:00
David Wood
b181867738 gen-arm: assert_instr on msvc for [su]mull[tb]
`dumpbin.exe` produces `44a1c000`/`44e1c000`/`44a1c400`/`44e1c400` for
`[su]mull[tb]` instead of the instruction name - so skip `assert_instr`
for these intrinsics on MSVC targets.
2026-04-14 02:59:59 +00:00
David Wood
e6c0129553 stdarch-test: [us]shll[tb] have no aliases
SVE's `[us]shll[tb]` intructions have no aliases unlike Neon's
`[us]hll{2}` so this logic needs adjusted to not accidentally rewrite
the instruction.
2026-04-14 01:47:11 +00:00
David Wood
acb48ca2ca gen-arm: disable assert_instr for pfalse
The implementation for this has the same behaviour as a `pfalse` but
doesn't currently emit one until an intrinsic is added to emit a
`zeroinitializer` for this.
2026-04-14 01:47:06 +00:00
mu001999
58af51e243 Emit fatal on invalid const args with nested defs 2026-04-14 09:43:02 +08:00
Chayim Refael Friedman
7bfecf641c Merge pull request #22033 from ChayimFriedman2/simplification
minor: Minor simplification
2026-04-14 01:11:37 +00:00
bors
0006519783 Auto merge of #155267 - jhpratt:rollup-fgQZJCS, r=jhpratt
Rollup of 5 pull requests

Successful merges:

 - rust-lang/rust#149357 (Implement `-Z allow-partial-mitigations` (RFC 3855))
 - rust-lang/rust#154939 (Refactor: simplify report_selection_error)
 - rust-lang/rust#152688 (Trait aliases: Also imply default trait bounds on type params other than `Self`)
 - rust-lang/rust#154352 (rustdoc: dep-info for standalone markdown inputs)
 - rust-lang/rust#155195 (tidy: handle `#[cfg_attr(bootstrap, doc = "...")]` in `compiler/` comments)
2026-04-14 01:06:31 +00:00
David Wood
88b4908583 assert-instr: support type generics
SVE intrinsics have both type and const generics and so the
`assert_instr` macro needs to be able to generate test cases with the
type generics instantiated with the types provided in the attribute.

Co-authored-by: Jamie Cunliffe <Jamie.Cunliffe@arm.com>
Co-authored-by: Luca Vizzarro <Luca.Vizzarro@arm.com>
Co-authored-by: Adam Gemmell <adam.gemmell@arm.com>
Co-authored-by: Jacob Bramley <jacob.bramley@arm.com>
2026-04-14 00:54:55 +00:00
David Wood
c21d4e99ea intrinsic-test: update parsing for SVE intrinsics
With SVE intrinsics in the `arm_intrinsics.json`, the parsing needs to be
updated to know to expect any new fields.
2026-04-14 00:54:55 +00:00
David Wood
b6b2ce3d44 core_arch: no SVE on arm64ec
arm64ec doesn't support SVE.
2026-04-14 00:54:55 +00:00
David Wood
a370aa3251 stdarch-verify: support sve
Co-authored-by: Adam Gemmell <Adam.Gemmell@arm.com>
Co-authored-by: Jamie Cunliffe <Jamie.Cunliffe@arm.com>
Co-authored-by: Jacob Bramley <jacob.bramley@arm.com>
Co-authored-by: Luca Vizzarro <Luca.Vizzarro@arm.com>
2026-04-14 00:54:55 +00:00
David Wood
6a6e8446b9 intrinsics_data: add sve intrinsics
Co-authored-by: Adam Gemmell <Adam.Gemmell@arm.com>
Co-authored-by: Jamie Cunliffe <Jamie.Cunliffe@arm.com>
Co-authored-by: Jacob Bramley <jacob.bramley@arm.com>
Co-authored-by: Luca Vizzarro <Luca.Vizzarro@arm.com>
2026-04-14 00:54:55 +00:00
Jacob Pratt
30d2f5aca6 Rollup merge of #155195 - jieyouxu:tidy-compiler-doc-attr, r=WaffleLapkin
tidy: handle `#[cfg_attr(bootstrap, doc = "...")]` in `compiler/` comments

For the unbalanced backtick check that Waffle ran into in https://github.com/rust-lang/rust/pull/154887.

This PR cherry-picks Waffle's tidy patch in that PR (and adds some explaining comments) even though I'd say this is somewhat hacky[^1]. But since the original tidy check implementation is already based on heuristics and so are likewise fuzzy, this is probably fine in practice for most cases.

[^1]: There can be false positives/negatives like having both fragments `cfg_attr` and `doc` inside a string literal, but I would expect that to be very very niche, so it's "good enough".

(I wanted to write a regression test, but this check needs some restructuring to make it more easy to test that I don't want to bundle in this PR.)

r? wafflelapkin (or bootstrap/compiler)
2026-04-13 20:12:07 -04:00
Jacob Pratt
4691e61f79 Rollup merge of #154352 - notriddle:emit-md, r=fmease
rustdoc: dep-info for standalone markdown inputs

Part of https://github.com/rust-lang/rust/pull/146220#issuecomment-3936957755

r? @fmease
2026-04-13 20:12:07 -04:00
Jacob Pratt
7e40efc366 Rollup merge of #152688 - fmease:implied-preds-default-bounds, r=jackh726
Trait aliases: Also imply default trait bounds on type params other than `Self`

Trait aliases already correctly imply default trait bounds on `Self` type params. However, due to an oversight, they didn't do that for normal type params.

Fixes rust-lang/rust#152687.
2026-04-13 20:12:06 -04:00
Jacob Pratt
2a0b5343df Rollup merge of #154939 - chenyukang:yukang-refactor-fn-pointer-cast-suggestion, r=davidtwco
Refactor: simplify report_selection_error

Split out `suggest_cast_to_fn_pointer` for better readability.
2026-04-13 20:12:05 -04:00
Jacob Pratt
7d1b042d45 Rollup merge of #149357 - arielb1:enforce-partial-mitigations, r=rcvalle
Implement `-Z allow-partial-mitigations` (RFC 3855)

This implements `-Z allow-partial-mitigations` as an unstable option, currently with support for control-flow-guard and stack-protector.

As a difference from the RFC, we have `-Z allow-partial-mitigations=!foo` rather than `-Z deny-partial-mitigations=foo`, since I couldn't find an easy way to have an allow/deny pair of flags where the latter flag wins.

To allow for stabilization, this is only enabled starting from the next edition. Maybe a better policy is possible (bikeshed).

r? @rcvalle
2026-04-13 20:12:05 -04:00
Mark Rousskov
edee654e08 Adjust release notes for post-merge feedback
* Adds musl CVE fix to compiler section
* Removes Cargo section per feedback in the PR
2026-04-13 19:59:10 -04:00
Chayim Refael Friedman
2fc3961758 Minor simplification 2026-04-14 02:40:51 +03:00
Tshepang Mbambo
d40530b0af Merge pull request #2834 from rust-lang/rustc-pull
Rustc pull update
2026-04-14 00:14:16 +02:00
The rustc-josh-sync Cronjob Bot
5b3b0853db Merge ref '17584a181979' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@17584a1819
Filtered ref: rust-lang/rustc-dev-guide@ec71ad7513
Upstream diff: 14196dbfa3...17584a1819

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-13 22:12:57 +00:00
The rustc-josh-sync Cronjob Bot
2a152e1454 Prepare for merging from rust-lang/rust
This updates the rust-version file to 17584a1819.
2026-04-13 22:12:50 +00:00
thebabalola
fdfdb0837c Replace custom trim_ascii_start with the standard library method
The local trim_ascii_start function in the markdown parser duplicates
<[u8]>::trim_ascii_start() from the standard library (stable since 1.80).
Remove the custom function and call the stdlib method directly.

No behaviour change.

Fixes https://github.com/rustfoundation/interop-initiative/issues/53
2026-04-13 23:07:39 +01:00
thebabalola
1e02a2b10b Add test for list item leading whitespace trimming 2026-04-13 23:07:39 +01:00
sayantn
7e24cd823d Add autocast for x86_amx 2026-04-14 03:25:02 +05:30
sayantn
1a28bc4529 Disable ABI checks for the unadjusted ABI 2026-04-14 03:25:02 +05:30
bors
338dff3e3a Auto merge of #136006 - oli-obk:push-tzonluoyuwkq, r=wesleywiser
Start using pattern types in libcore



cc rust-lang/rust#135996

Replaces the innards of `NonNull` with `*const T is !null`.

This does affect LLVM's optimizations, as now reading the field preserves the metadata that the field is not null, and transmuting to another type (e.g. just a raw pointer), will also preserve that information for optimizations. This can cause LLVM opts to do more work, but it's not guaranteed to produce better machine code.

Once we also remove all uses of rustc_layout_scalar_range_start from rustc itself, we can remove the support for that attribute entirely and handle all such needs via pattern types
2026-04-13 21:54:46 +00:00
bors
01dfd311b7 Auto merge of #136006 - oli-obk:push-tzonluoyuwkq, r=wesleywiser
Start using pattern types in libcore



cc rust-lang/rust#135996

Replaces the innards of `NonNull` with `*const T is !null`.

This does affect LLVM's optimizations, as now reading the field preserves the metadata that the field is not null, and transmuting to another type (e.g. just a raw pointer), will also preserve that information for optimizations. This can cause LLVM opts to do more work, but it's not guaranteed to produce better machine code.

Once we also remove all uses of rustc_layout_scalar_range_start from rustc itself, we can remove the support for that attribute entirely and handle all such needs via pattern types
2026-04-13 21:54:46 +00:00
Daniel Scherzer
0d2a972a84 bootstrap.py: fix duplicated "the" 2026-04-13 14:52:53 -07:00
Chayim Refael Friedman
164395b08d Merge pull request #21835 from mehmet-ylcnky/feat/raw-ptr-mutability-api
feat: add is_mutable_raw_ptr and as_raw_ptr to hir::Type
2026-04-13 21:25:21 +00:00
Chris Denton
5dd0500926 Windows: Cache the pipe filesystem handle
Also use the `\Device\NamedPipe\` directly instead of the symlink to it.
2026-04-13 21:25:05 +00:00
mehmet-yalcinkaya_volvo
536ce324d0 feat: add is_mutable_raw_ptr and as_raw_ptr to hir::Type 2026-04-14 00:16:21 +03:00
Augie Fackler
fb9e970c1f explicit-tail-calls: disable two tests on LoongArch
A recent LLVM change broke these on LLVM 23.
2026-04-13 17:00:43 -04:00
zedddie
9a9f5b5141 gate primitives behind min_adt_const_params; change suggestion to min_adt_const_params 2026-04-13 22:26:05 +02:00
John Kåre Alsaker
b9ec55bbcd Document why layout.align() + layout.size() doesn't overflow 2026-04-13 22:00:28 +02:00
A4-Tacks
3536b19027 Merge pull request #21999 from A4-Tacks/refmatch-kwdprefix-quickfix
fix: Fix ref_match position when keyword prefix
2026-04-13 19:01:48 +00:00
Ralf Jung
a6d043a420 Merge pull request #4956 from michaliskok/genmc-no-split-nas
GenMC: Don't split up non-atomic accesses to smaller chunks
2026-04-13 18:53:34 +00:00
Jonathan Brouwer
a0f105e63e Remove AttributeTemplate from BUILTIN_ATTRIBUTES 2026-04-13 20:52:23 +02:00
A4-Tacks
063763fb49 fix: Fix ref_match position when keyword prefix
This is a quick fix, please review if there is a regression

Example
---
```rust
fn foo(data: &i32) {}
fn main() {
    let indent = 2i32;
    foo(in$0)
}
```

**Before this PR**

```rust
fn foo(data: &i32) {}
fn main() {
    let indent = 2i32;
    foo(in&dent)
}
```

```rust
source_range: 65..67,
delete: 65..67,
ref_match: "&@67",
..
```

**After this PR**

```rust
fn foo(data: &i32) {}
fn main() {
    let indent = 2i32;
    foo(&indent)
}
```

```rust
source_range: 65..67,
delete: 65..67,
ref_match: "&@65",
..
```
2026-04-14 02:52:10 +08:00
Jonathan Brouwer
ad41fc08b3 Remove EncodeCrossCrate from BUILTIN_ATTRIBUTES 2026-04-13 20:51:30 +02:00
Jonathan Brouwer
034de09cb3 Remove AttributeType from BUILTIN_ATTRIBUTES 2026-04-13 20:51:29 +02:00
Jonathan Brouwer
1e793cdad3 Remove AttributeDuplicates from BUILTIN_ATTRIBUTES 2026-04-13 20:51:24 +02:00
Jonathan Brouwer
da8cf97e64 Remove AttributeDuplicates from BUILTIN_ATTRIBUTES 2026-04-13 20:51:24 +02:00
Jonathan Brouwer
e391f7717f Remove emit_fatal_malformed_builtin_attribute 2026-04-13 20:51:21 +02:00
bors
17584a1819 Auto merge of #155253 - JonathanBrouwer:rollup-lERdTAB, r=JonathanBrouwer
Rollup of 19 pull requests

Successful merges:

 - rust-lang/rust#155162 (relnotes for 1.95)
 - rust-lang/rust#140763 (Change codegen of LLVM intrinsics to be name-based, and add llvm linkage support for `bf16(xN)` and `i1xN`)
 - rust-lang/rust#153604 (Fix thread::available_parallelism on WASI targets with threads)
 - rust-lang/rust#154193 (Implement EII for statics)
 - rust-lang/rust#154389 (Add more robust handling of nested query cycles)
 - rust-lang/rust#154435 (resolve: Some import resolution cleanups)
 - rust-lang/rust#155236 (Normalize individual predicate of `InstantiatedPredicates` inside `predicates_for_generics`)
 - rust-lang/rust#155243 (cg_ssa: transmute between scalable vectors)
 - rust-lang/rust#153941 (tests/debuginfo/basic-stepping.rs: Explain why all lines are not steppable)
 - rust-lang/rust#154587 (Add --verbose-run-make-subprocess-output flag to suppress verbose run-make output for passing tests)
 - rust-lang/rust#154624 (Make `DerefPure` dyn-incompatible)
 - rust-lang/rust#154929 (Add `const Default` impls for `LazyCell` and `LazyLock`)
 - rust-lang/rust#154944 (Small refactor of `arena_cache` query values)
 - rust-lang/rust#155055 (UI automation)
 - rust-lang/rust#155062 (Move tests from `tests/ui/issues/` to appropriate directories)
 - rust-lang/rust#155131 (Stabilize feature `uint_bit_width`)
 - rust-lang/rust#155147 (Stabilize feature `int_lowest_highest_one`)
 - rust-lang/rust#155174 (Improve emission of `UnknownDiagnosticAttribute` lint)
 - rust-lang/rust#155194 (Fix manpage version replacement and use verbose version)
2026-04-13 18:32:47 +00:00
bors
2c5e3d3c5c Auto merge of #155253 - JonathanBrouwer:rollup-lERdTAB, r=JonathanBrouwer
Rollup of 19 pull requests

Successful merges:

 - rust-lang/rust#155162 (relnotes for 1.95)
 - rust-lang/rust#140763 (Change codegen of LLVM intrinsics to be name-based, and add llvm linkage support for `bf16(xN)` and `i1xN`)
 - rust-lang/rust#153604 (Fix thread::available_parallelism on WASI targets with threads)
 - rust-lang/rust#154193 (Implement EII for statics)
 - rust-lang/rust#154389 (Add more robust handling of nested query cycles)
 - rust-lang/rust#154435 (resolve: Some import resolution cleanups)
 - rust-lang/rust#155236 (Normalize individual predicate of `InstantiatedPredicates` inside `predicates_for_generics`)
 - rust-lang/rust#155243 (cg_ssa: transmute between scalable vectors)
 - rust-lang/rust#153941 (tests/debuginfo/basic-stepping.rs: Explain why all lines are not steppable)
 - rust-lang/rust#154587 (Add --verbose-run-make-subprocess-output flag to suppress verbose run-make output for passing tests)
 - rust-lang/rust#154624 (Make `DerefPure` dyn-incompatible)
 - rust-lang/rust#154929 (Add `const Default` impls for `LazyCell` and `LazyLock`)
 - rust-lang/rust#154944 (Small refactor of `arena_cache` query values)
 - rust-lang/rust#155055 (UI automation)
 - rust-lang/rust#155062 (Move tests from `tests/ui/issues/` to appropriate directories)
 - rust-lang/rust#155131 (Stabilize feature `uint_bit_width`)
 - rust-lang/rust#155147 (Stabilize feature `int_lowest_highest_one`)
 - rust-lang/rust#155174 (Improve emission of `UnknownDiagnosticAttribute` lint)
 - rust-lang/rust#155194 (Fix manpage version replacement and use verbose version)
2026-04-13 18:32:47 +00:00
Chayim Refael Friedman
2b6088bea2 Merge pull request #22019 from rust-lang/ci/gen-lints
Update generated lints
2026-04-13 18:27:53 +00:00
Chayim Refael Friedman
51f8800ae1 Merge pull request #22018 from A4-Tacks/vsc-suggest-string
fix: enable vscode suggest in strings
2026-04-13 18:27:21 +00:00
A4-Tacks
a91c488cf2 Merge pull request #22003 from Amit5601/fix/hidden-enum-clean
fix: complete variants of hidden enums through public aliases
2026-04-13 18:25:28 +00:00
Jonathan Brouwer
9f11d53cd3 Rollup merge of #155194 - davidkna:man-version, r=clubby789
Fix manpage version replacement and use verbose version

- Fix a bug where `t!(fs::copy(&page_src, &page_dst))` was called after`fs::write`, silently overwriting the substituted content with the original template (restoring the `<INSERT VERSION HERE>` placeholder verbatim) (Related rust-lang/rust#93685)
- Use `rust_info().version()` instead of the bare version number, so the man page now includes the full version string with commit hash and date
2026-04-13 20:20:08 +02:00
Jonathan Brouwer
e3d1d77058 Rollup merge of #155174 - mejrs:on_move_gating, r=JonathanBrouwer
Improve emission of `UnknownDiagnosticAttribute` lint

This checks features much less than the current implementation. See https://github.com/rust-lang/rust/pull/155155 for context. Minor fixes and comments are added in the second and third commit.
2026-04-13 20:20:07 +02:00
Jonathan Brouwer
0af1a15c9a Rollup merge of #155147 - sorairolake:stabilize-int-lowest-highest-one, r=jhpratt
Stabilize feature `int_lowest_highest_one`

Tracking issue: rust-lang/rust#145203
FCP is finished in https://github.com/rust-lang/rust/issues/145203#issuecomment-4224883617

Closes rust-lang/rust#145203

@rustbot modify labels: +T-libs-api
2026-04-13 20:20:06 +02:00
Jonathan Brouwer
0bfc5efe04 Rollup merge of #155131 - sorairolake:stabilize-uint-bit-width, r=jhpratt
Stabilize feature `uint_bit_width`

Tracking issue: rust-lang/rust#142326
FCP is finished in https://github.com/rust-lang/rust/issues/142326#issuecomment-4224883142

Closes rust-lang/rust#142326

@rustbot modify labels: +T-libs-api
2026-04-13 20:20:05 +02:00
Jonathan Brouwer
b8e88c7f49 Rollup merge of #155062 - ujjwalvishwakarma2006:reorg-tests, r=Kivooeo
Move tests from `tests/ui/issues/` to appropriate directories

In this PR, I am moving the following test from `tests/ui/issues` directory to the appropriate directories, followed by the addition of issue links at the top and reblessing of the stderr files:

| old-name | new-sub-dir | new-name |
|-|-|-|
| `issue-29516.rs` | `auto-traits/` | `distinct-type-tuple-by-negative-impl.rs` |
| `issue-3874.rs` | `binding/` | `ref-in-let-lhs-in-field.rs` |
| `issue-32782.rs` | `feature-gates/` | `feature-gate-check-nested-macro-invocation.rs` |
| `issue-32782.stderr` | `feature-gates/` | `feature-gate-check-nested-macro-invocation.stderr` |
| `issue-5100.rs` | `pattern/` | `match-errors-derived-error-suppression.rs` |
| `issue-5100.stderr` | `pattern/` | `match-errors-derived-error-suppression.stderr` |
| `issue-21033.rs` | `pattern/` | `match-struct-var-having-boxed-field.rs` |

r? Kivooeo
r? Teapot4195
2026-04-13 20:20:04 +02:00
Jonathan Brouwer
2ab9ebfd98 Rollup merge of #155055 - rishi-techo-14:ui-automation, r=Kivooeo
UI automation

# To move issue-3154 and issue-16774 to functional subdirectories:

I have moved 2 tests from tests/ui/issues to their appropriate directories using "test-manager" tool.
## Changes:

- Moved tests/ui/issues/issue-3154.rs to tests/ui/borrowck/missing-lifetime-in-return.rs

- Moved tests/ui/issues/issue-16774.rs to tests/ui/deref/derefmut-closure-drop-order.rs
These moves where performed using the test-manager automation tool.
2026-04-13 20:20:04 +02:00
Jonathan Brouwer
b1bb531999 Rollup merge of #154944 - zetanumbers:refactor_arena_cache_queries, r=jackh726
Small refactor of `arena_cache` query values

Query modifier `arena_cache` automatically allocates only `Some` variant of query's value of type `Option<&'tcx T>`, so `mir_callgraph_cyclic` should've been doing it from the beginning. The same could be said for any `Result<&'tcx T, ErrorGuaranteed>` as `ErrorGuaranteed` is a zero sized type, but that requires adding a new `ArenaCached` implementation.
2026-04-13 20:20:03 +02:00
Jonathan Brouwer
8d8dcf142a Rollup merge of #154929 - davidgauch:const-default-lazy, r=jhpratt
Add `const Default` impls for `LazyCell` and `LazyLock`

Follow up to these commits by @estebank https://github.com/rust-lang/rust/pull/134628 and https://github.com/rust-lang/rust/pull/151190.
Tracking issue https://github.com/rust-lang/rust/issues/143894.

cc @fmease @fee1-dead @oli-obk

This enables `static L: LazyLock<D> = Default::default()`  for any type `D: Default` which is safe as `D::default()` is only evaluated at runtime.
2026-04-13 20:20:02 +02:00
Jonathan Brouwer
3f88653f77 Rollup merge of #154624 - theemathas:deref-pure-dyn-incompat, r=jackh726
Make `DerefPure` dyn-incompatible

Fixes https://github.com/rust-lang/rust/issues/154619.

If `DerefPure` were dyn-compatible, a trait object of a subtrait of `DerefPure` could be created by unsize-coercing an existing type that implements `DerefPure`. But then the trait object could have its own non-pure impl of `Deref`/`DerefMut`, which is unsound, since the trait object would implement `DerefPure`. Thus, we make `DerefPure` dyn-incompatible.

r? types
2026-04-13 20:20:01 +02:00
Jonathan Brouwer
46997fb00f Rollup merge of #154587 - Ayuse:compiletest-quiet-run-make, r=jieyouxu
Add --verbose-run-make-subprocess-output flag to suppress verbose run-make output for passing tests

- Adds `--verbose-run-make-subprocess-output` flag to `./x test` and compiletest
- `./x test --no-capture --verbose-run-make-subprocess-output=false` suppresses verbose subprocess output for passing run-make tests
- Failed tests always print their output regardless of `--verbose-run-make-subprocess-output`
- Default behavior (verbose) is unchanged

This addresses the request from @bjorn3  which needs `--no-capture` (due to `panic=abort`) but doesn't want output dumped for every passing test.

Helps with rust-lang/rust#154069

## Test plan

- [x] `./x test tests/run-make/bare-outfile --no-capture --force-rerun` — verbose output for passing test
- [x] `./x test tests/run-make/bare-outfile --no-capture --verbose-run-make-subprocess-output=false --force-rerun` — no verbose output for passing test
- [x] Failing test still dumps output with `--verbose-run-make-subprocess-output=false`
2026-04-13 20:20:00 +02:00
Jonathan Brouwer
978fb762ac Rollup merge of #153941 - Enselic:fully-steppable, r=saethlin
tests/debuginfo/basic-stepping.rs: Explain why all lines are not steppable

Some optimization passes [_improve_](https://github.com/rust-lang/compiler-team/issues/319) compile times. So we want to run some passes even with `-Copt-level=0`. That means that some debuggable lines can be optimized away. Document that as expected behavior.

Closes https://github.com/rust-lang/rust/issues/33013.

Replaces https://github.com/rust-lang/rust/pull/151426. See that PR for some discussion.
2026-04-13 20:20:00 +02:00
Jonathan Brouwer
769d225a4a Rollup merge of #155243 - davidtwco:scalable-vectors-transmute, r=Amanieu
cg_ssa: transmute between scalable vectors

Like regular SIMD vectors, we can support casting between scalable vectors of integral or floating-point types without needing a temporary.

r? @Amanieu
2026-04-13 20:19:59 +02:00
Jonathan Brouwer
2fce4af463 Rollup merge of #155236 - adwinwhite:refactor-predicates-for-generics, r=lcnr
Normalize individual predicate of `InstantiatedPredicates` inside `predicates_for_generics`

This is a cleanup to better land rust-lang/rust#155083. It allows us to wrap individual clause in `Unnormalized` wrapper. See [this comment](https://github.com/rust-lang/rust/pull/155083#discussion_r3072219035)

Besides that, this PR also adds missing normalization in some cases.

r? @lcnr
2026-04-13 20:19:58 +02:00
Jonathan Brouwer
93884baee5 Rollup merge of #154435 - petrochenkov:cleandecl, r=jackh726
resolve: Some import resolution cleanups

See the individual commits
2026-04-13 20:19:57 +02:00
Jonathan Brouwer
e39dfc5e4a Rollup merge of #154389 - Zoxc:nested-cycles, r=petrochenkov
Add more robust handling of nested query cycles

This adds more robust handling of query cycle that occur while we are already printing a query cycle error. Such nested query cycle are compiler bugs and this adds special handling so that both the nested query cycle and the outer query cycle are printed. Doubly nested query cycle errors are ignored to prevent infinite recursion.
2026-04-13 20:19:57 +02:00
Jonathan Brouwer
b23bc0bbd0 Rollup merge of #154193 - JonathanBrouwer:external-static, r=jdonszelmann
Implement EII for statics

This PR implements EII for statics. I've tried to mirror the implementation for functions in a few places, this causes some duplicate code but I'm also not really sure whether there's a clean way to merge the implementations.

This does not implement defaults for static EIIs yet, I will do that in a followup PR
2026-04-13 20:19:56 +02:00
Jonathan Brouwer
d2fa85cd4d Rollup merge of #154193 - JonathanBrouwer:external-static, r=jdonszelmann
Implement EII for statics

This PR implements EII for statics. I've tried to mirror the implementation for functions in a few places, this causes some duplicate code but I'm also not really sure whether there's a clean way to merge the implementations.

This does not implement defaults for static EIIs yet, I will do that in a followup PR
2026-04-13 20:19:56 +02:00
Jonathan Brouwer
148ef32d65 Rollup merge of #153604 - rust-wasi-web:wasi-available-parallelism-fix, r=alexcrichton
Fix thread::available_parallelism on WASI targets with threads

The refactoring in ba462864f1 ("std: Use more unix.rs code on WASI targets") moved WASI from its own thread module into the shared unix.rs module. However, it did not carry over the available_parallelism() implementation for WASI with threads, causing it to fall through to the unsupported catch-all. This silently regressed the support originally added in f0b7008648.

Fix this by adding WASI to the standard UNIX cfg_select branch.

Depends on rust-lang/rust#155057 (Update libc to v0.2.184).
2026-04-13 20:19:55 +02:00
Jonathan Brouwer
f0af5f5777 Rollup merge of #140763 - sayantn:test-amx, r=dianqk
Change codegen of LLVM intrinsics to be name-based, and add llvm linkage support for `bf16(xN)` and `i1xN`

*[View all comments](https://triagebot.infra.rust-lang.org/gh-comments/rust-lang/rust/pull/140763)*

This PR changes how LLVM intrinsics are codegen

# Explanation of the changes

## Current procedure

This is the same for all functions, LLVM intrinsics are _not_ treated specially
 - We get the LLVM Type of a function simply using the argument types. For example, the following function
   ```rust
   #[link_name = "llvm.sqrt.f32"]
   fn sqrtf32(a: f32) -> f32;
   ```
   will have LLVM type simply `f32 (f32)` due to the Rust signature

### Pros

 - Simpler to implement, no extra complexity involved due to LLVM intrinsics

### Cons

 - LLVM intrinsics have a well-defined signature, completely defined by their name (and if it is overloaded, the type parameters). So, this process of converting Rust signatures to LLVM signatures may not work, for example the following code generates LLVM IR without any problem
   ```rust
   #[link_name = "llvm.sqrt.f32"]
   fn sqrtf32(a: i32) -> f32;
   ```
   but the generated LLVM IR is invalid, because it has wrong signature for the intrinsic ([Godbolt](https://godbolt.org/z/6ff9hrcd5), adding `-Zverify-llvm-ir` to it will fail compilation). I would expect this code to not compile at all instead of generating invalid IR.
 - LLVM intrinsics that have types in their signature that can't be accessed from Rust (notable examples are the AMX intrinsics that have the `x86amx` type, and (almost) all intrinsics that have vectors of `i1` types) can't be linked to at all. This is a (major?) roadblock in the AMX and AVX512 support in stdarch.
 - If code uses an non-existing LLVM intrinsic, even `-Zverify-llvm-ir` won't complain. Eventually it will error out due to the non-existing function (courtesy of the linker). I don't think this is a behavior we want.

## What this PR does

 - When linking to **non-overloaded** intrinsics, we use the function `LLVMIntrinsicGetType` to directly get the function type of the intrinsic from LLVM.
 - We then use this LLVM definition to _verify_ the Rust signature, and emit a proper error if it doesn't match, instead of silently emitting invalid IR.
 - Lint if linking to deprecated or invalid LLVM intrinsics

> [!NOTE]
> This PR only focuses on non-overloaded intrinsics, overloaded can be done in a future PR

Regardless, the undermentioned functionalities work for **all** intrinsics

 - If we can't find the intrinsic, we check if it has been `AutoUpgrade`d by LLVM. If not, that means it is an invalid intrinsic, and we error out.
 - Don't allow intrinsics from other archs to be declared, e.g. error out if an AArch64 intrinsic is declared when we are compiling for x86

### Pros

 - It is now not possible (or at least, it would require _significantly_ more leaps and bounds) to introduce invalid IR using **non-overloaded** LLVM intrinsics.
 - As we are now doing the matching of Rust signatures to LLVM intrinsics ourselves, we can now add bypasses to enable linking to such non-Rust types (e.g. matching 8192-bit vectors to `x86amx` and injecting `llvm.x86.cast.vector.to.tile` and `llvm.x86.cast.tile.to.vector`s in callsite)

> [!NOTE]
> I don't intend for these bypasses to be permanent. A better approach will be introducing a `bf16` type in Rust, and allowing `repr(simd)` with `bool`s to get Rust-native `i1xN`s. These are meant to be short-time, as I mentioned, "bypass"es. They shouldn't cause any major breakage even if removed, as `link_llvm_intrinsics` is perma-unstable.

   This PR adds bypasses for `bf16` (via `i16`), `bf16xN` (via `i16xN`) and `i1xN` (via `iM`, where `M` is the smallest power of 2  s.t. `M >= N`, unless `N <= 4`, where we use `M = 8`). This will unblock AVX512-VP2INTERSECT and a lot of bf16 intrinsics in stdarch. This PR also automatically destructures structs if the types don't exactly match (this is required for us to start emitting hard errors on mismmatches).

### Cons

 - This only works for non-overloaded intrinsics (at least for now). Improving this to work with overloaded intrinsics too will involve significantly more work.

# Possible ways to extend this to overloaded intrinsics (future)

## Parse the mangled intrinsic name to get the type parameters

LLVM has a stable mangling of intrinsic names with type parameters (in `LLVMIntrinsicCopyOverloadedName2`), so we can parse the name to get the type parameters, and then just do the same thing.

### Pros
 - For _most_ intrinsics, this will work perfectly, and is a easy way to do this.

### Cons
 - The LLVM mangling is not perfectly reversible. When we have `TargetExt` types or identified structs, their name is a part of the mangling, making it impossible to reverse. Even more complexities arise when there are unnamed identified structs, as LLVM adds more mangling to the names.
 - @nikic's work on LLVM intrinsics will remove the name mangling, making this approach impossible

## Use the `IITDescriptor` table and the Rust function signature

We can use the base name to get the `IITDescriptor`s of the corresponding intrinsic, and then manually implement the _matching_ logic based on the Rust signature.

### Pros

 - Doesn't have the above mentioned limitation of the parsing approach, has correct behavior even when there are identified structs and `TargetExt` types. Also, fun fact, Rust exports all struct types as literal structs (unless it is emitting LLVM IR, then it always uses named identified structs, with mangled names)

### Cons

 - **Doesn't** actually use the type parameters in the name, only uses the base name and the Rust signature to get the llvm signature (although we _can_ check that it is the correct name). It means there would be no way to (for example) link against `llvm.sqrt.bf16` until we have `bf16` types in Rust. Because if we are using `u16`s (or any other type) as `bf16`s, then the matcher will deduce that the signature is `u16 (u16)` not `bf16 (bf16)` (which would lead to an error because `u16` is not a valid type parameter for `llvm.sqrt`), even though the intended type parameter is specified in the name.
 - Much more complex, and hard to maintain as LLVM gets new `IITDescriptorKind`s

These 2 approaches might give different results for same function. Let's take
```rust
#[link_name = "llvm.is.constant.bf16"]
fn foo(a: u16) -> bool
```
The name-based approach will decide that the type parameter is `bf16`, and the LLVM signature is `i1 (bf16)` and will inject some bitcasts at callsite.
The `IITDescriptor`-based approach will decide that the LLVM signature is `i1 (u16)`, and will see that the name given doesn't match the expected name (`llvm.is.constant.u16`), and will error out.

Reviews are welcome, as this is my first time _actually_ contributing to `rustc`

@rustbot label T-compiler A-codegen A-LLVM
r? codegen
2026-04-13 20:19:54 +02:00
Jonathan Brouwer
2b77fc4702 Rollup merge of #155162 - BoxyUwU:relnotes_1_95, r=Mark-Simulacrum
relnotes for 1.95

r? @Mark-Simulacrum

cc @rust-lang/release
2026-04-13 20:19:54 +02:00
Josh Stone
6e618bea47 compiler: update hashbrown to 0.17
See library's rust-lang/rust#155154 for the bug fixes this brings.
This PR also updates `indexmap` in the compiler as a direct dependent.
2026-04-13 11:11:16 -07:00
Chayim Refael Friedman
5b573d889e Merge pull request #22030 from Wilfred/pre-mir-relocation-test
fix: MIR evaluation of sized &T with recursive const fn
2026-04-13 18:00:12 +00:00
Chayim Refael Friedman
7cd9c0440c Merge pull request #22031 from WeiTheShinobi/introduce_has_local_inherent_impl_on_render
Demoting completion relevance when an inherent impl already exists
2026-04-13 17:51:55 +00:00
Michalis Kokologiannakis
385756cee1 genmc*: Don't split up non-atomic accesses to smaller chunks
GenMC is now able to handle larger and mixed-size non-atomic
accesses.
2026-04-13 19:47:17 +02:00
jackh726
c681ae6931 For supertrait-shadowing tests, assert str rather than println 2026-04-13 17:19:30 +00:00
Takayuki Maeda
5c80d9031d add a link to issue 154487 2026-04-14 02:08:26 +09:00
Kao-Wei Yeh
482a3597ca Added a field has_local_inherent_impl to CompletionRelevance. 2026-04-14 00:48:45 +08:00
Samuel Tardieu
7f0774a151 Fix wrong suggestion for println_empty_string with non-parenthesis delimiters (#16846)
Fixes rust-lang/rust-clippy#16843

changelog: [`println_empty_string`]: fix wrong suggestion with
non-parenthesis delimiters
2026-04-13 15:59:32 +00:00
yukang
270cc62257 refactor: simplify fn pointer cast suggestion logic 2026-04-13 23:55:22 +08:00
Folkert de Vries
7c4cf96587 report the varargs_without_pattern lint in deps 2026-04-13 17:43:36 +02:00
León Orell Valerian Liehr
9d627dd796 Trait aliases: Imply default trait bounds on type params other than Self 2026-04-13 17:35:28 +02:00
Amit Singhmar
92da3d3479 fix: complete variants of hidden enums through public aliases
Fixes rust-lang/rust-analyzer#21891.

Previously, the completion engine would aggressively bail out if the parent enum was marked . This pushes the visibility check down to the individual variants so they can be properly completed when accessed via a public type alias.
2026-04-13 15:26:02 +00:00
Lukas Wirth
0813ab8d92 Merge pull request #22029 from Wilfred/more_rustdoc_fixes
internal: Ensure rustdoc GitHub action runs on PRs
2026-04-13 15:25:57 +00:00
Oli Scherer
834137afd7 Use !null pattern type in libcore 2026-04-13 17:23:03 +02:00
Oli Scherer
fe2553fe58 Use !null pattern type in libcore 2026-04-13 17:23:03 +02:00
bors
a72e2a71d8 Auto merge of #155239 - JonathanBrouwer:rollup-XUNKT4X, r=JonathanBrouwer
Rollup of 10 pull requests

Successful merges:

 - rust-lang/rust#155227 (`rust-analyzer` subtree update)
 - rust-lang/rust#153335 (Add #![unstable_removed(..)] attribute to track removed features)
 - rust-lang/rust#154932 (Handle RTN projections in assoc type restriction diagnostics)
 - rust-lang/rust#155096 (delegation: support proper interaction of user-specified args and impl Traits)
 - rust-lang/rust#155106 (cg_llvm: scalable vectors with `simd_cast` and `simd_select`)
 - rust-lang/rust#155140 (add regression test for OpenOptionsExt downstream compat)
 - rust-lang/rust#155182 (Make the expansion of guard metavars begin guard non-terminals)
 - rust-lang/rust#155226 (delegation: revert execution of hir_crate_items before delayed lowering)
 - rust-lang/rust#153997 (Use closures more consistently in `dep_graph.rs`.)
 - rust-lang/rust#155003 (update thin-vec)
2026-04-13 15:18:43 +00:00
Wilfred Hughes
b198955c90 internal: Ensure rustdoc GitHub action runs on PRs
We want to complain on PRs that generate rustdoc warnings, but only
deploy the generate HTML on the master branch.

Also fix the existing rustdoc warning.

AI disclosure: Some Claude Opus usage.
2026-04-13 16:03:02 +01:00
Wilfred Hughes
1ba2ec7fb1 fix: MIR evaluation of sized &T with recursive const fn
Previously, we didn't recurse in Evaluator::create_memory_map() or
Evaluator::patch_addresses() when handling references with a known
size.

This caused problems for hover rendering on const values, which would
build a memory map for evaluated allocations and then pretty-printed
values by following references through that map.

As a result, references in the map still pointed to the original addresses,
meaning that the value pretty-printer would see the type parameters
before substitution. This could cause stack overflows on well-formed
Rust code using recursive const functions.

Add a regression test for hovering on a recursive const fn that
previously caused stack overflow.

Fixes rust-lang/rust-analyzer#21503

AI disclosure: I used Codex with GPT 5.4 to investigate the issue and
write the initial version of this commit.
2026-04-13 15:48:37 +01:00
Lukas Wirth
2233282dc4 Merge pull request #22028 from Wilfred/fix_rustdoc_quoting
internal: Fix rustdoc quoting
2026-04-13 13:07:50 +00:00
Adwin White
7aa3f3ce52 normalize each predicate inside predicates_for_generics 2026-04-13 21:03:51 +08:00
Wilfred Hughes
9cd6a392e3 internal: Fix rustdoc quoting
GitHub actions are currently failing with:

    error: unresolved link to `cfg_attr`
       --> crates/ide-completion/src/context.rs:414:61
        |
    414 |     /// Set if we are inside the predicate of a #[cfg] or #[cfg_attr].
        |                                                             ^^^^^^^^ no item named `cfg_attr` in scope
        |
        = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]`
        = note: `-D rustdoc::broken-intra-doc-links` implied by `-D warnings`
        = help: to override `-D warnings` add `#[allow(rustdoc::broken_intra_doc_links)]`

     Documenting ide v0.0.0 (/home/runner/work/rust-analyzer/rust-analyzer/crates/ide)
    error: could not document `ide-completion`

Use backticks to fix this.

AI disclosure: written with Claude Opus because it was marginally
faster.
2026-04-13 13:36:10 +01:00
Folkert de Vries
c766242209 add the fma4 x86 target feature 2026-04-13 14:12:08 +02:00
Jonathan Brouwer
0e4b612119 Rollup merge of #155003 - malezjaa:update-thinvec, r=davidtwco
update thin-vec

With thin-vec v0.2.15 released, copy-pasted implementation of ExtractIf can be removed.
2026-04-13 14:02:35 +02:00
Jonathan Brouwer
f8a8c9e244 Rollup merge of #155003 - malezjaa:update-thinvec, r=davidtwco
update thin-vec

With thin-vec v0.2.15 released, copy-pasted implementation of ExtractIf can be removed.
2026-04-13 14:02:35 +02:00
Jonathan Brouwer
2f607ee662 Rollup merge of #153997 - nnethercote:closure-consistency, r=petrochenkov
Use closures more consistently in `dep_graph.rs`.

This file has several methods that take a `FnOnce() -> R` closure:
- `DepGraph::with_ignore`
- `DepGraph::with_query_deserialization`
- `DepGraph::with_anon_task`
- `DepGraphData::with_anon_task_inner`

It also has two methods that take a faux closure via an `A` argument and a `fn(TyCtxt<'tcx>, A) -> R` argument:
- DepGraph::with_task
- DepGraphData::with_task

The rationale is that the faux closure exercises tight control over what state they have access to. This seems silly when (a) they are passed a `TyCtxt`, and (b) when similar nearby functions take real closures. And they are more awkward to use, e.g. requiring multiple arguments to be gathered into a tuple. This commit changes the faux closures to real closures.

r? @Zalathar
2026-04-13 14:02:35 +02:00
Jonathan Brouwer
14b5df4749 Rollup merge of #155226 - aerooneqq:delegation-hir-crate-items-revert, r=petrochenkov
delegation: revert execution of hir_crate_items before delayed lowering

This PR reverts rust-lang/rust#154368, as after weekend consideration I don't think that it is a correct way of fixing cycles during delayed lowering:

- The number of ICEs were reported, fixing them would require to develop solution from rust-lang/rust#154368 but I am afraid that it would lead to cancer code growing,
- The [memory regression](https://github.com/rust-lang/rust/pull/154368#issuecomment-4229353764) for rustdoc was reported, it can be fixed with moving `tcx.force_delayed_owners_lowering` call earlier, but it is already bad that this is call is now required everywhere, before rust-lang/rust#154368 AST was dropped before `hir_crate_items` automatically and users of `rustc` API did not have to think about it.

I will try to come up with a more robust solution leaving rust-lang/rust#154368 as a last resort if nothing else will work.

Re-opens rust-lang/rust#154169.
Fixes rust-lang/rust#155125. Fixes rust-lang/rust#155127. Fixes rust-lang/rust#155128. Fixes rust-lang/rust#155164. Fixes rust-lang/rust#155202.
Part of rust-lang/rust#118212.

r? @petrochenkov
2026-04-13 14:02:34 +02:00
Jonathan Brouwer
49b5708d51 Rollup merge of #155182 - fmease:guard-exp-begins-guard, r=petrochenkov
Make the expansion of guard metavars begin guard non-terminals

While investigating something unrelated, I noticed a bug in the impl of unstable feature `macro_guard_matcher` (tracking issue: rust-lang/rust#153104). Namely, the following doesn't compile:

```rs
#![feature(macro_guard_matcher)]

macro_rules! a { ($guard:guard) => { b!($guard); }; }
macro_rules! b { ($guard:guard) => {}; }
a!(if true);
```

```
error: no rules expected `guard` metavariable
 --> src/lib.rs:3:41
  |
3 | macro_rules! a { ($guard:guard) => { b!($guard); }; }
  |                                         ^^^^^^ no rules expected this token in macro call
4 | macro_rules! b { ($guard:guard) => {}; }
  | -------------- when calling this macro
5 | a!(if true);
  | ----------- in this macro invocation
  |
note: while trying to match meta-variable `$guard:guard`
 --> src/lib.rs:4:19
  |
4 | macro_rules! b { ($guard:guard) => {}; }
  |                   ^^^^^^^^^^^^
  = note: this error originates in the macro `a` (in Nightly builds, run with -Z macro-backtrace for more info)
```

---

While I'm still skeptical of `guard` fragment specifiers in general (although I can't quite pinpoint why), I figured I should fix this issue.
2026-04-13 14:02:33 +02:00
Jonathan Brouwer
49f0536229 Rollup merge of #155140 - Vastargazing:open-options-ext-test, r=jdonszelmann,kivooeo
add regression test for OpenOptionsExt downstream compat

Following up on rust-lang/rust#153491, which added a warning comment there, but no automated guardrail to prevent another breaking change like rust-lang/rust#149718

This adds a simple windows-only ui test that manually implements `OpenOptionsExt`. That way, if someone accidentally adds another required method to the trait, we catch it before it reaches stable and breaks downstream crates like Tokio again.

Closes rust-lang/rust#153486
2026-04-13 14:02:33 +02:00
Jonathan Brouwer
83a57cae65 Rollup merge of #155106 - davidtwco:scalable-vector-more-simd-intrinsics, r=Amanieu
cg_llvm: scalable vectors with `simd_cast` and `simd_select`

Previously `sve_cast`'s implementation was abstracted to power both `sve_cast` and `simd_cast` which supported scalable and non-scalable vectors respectively. In anticipation of having to do this for another `simd_*` intrinsic, `sve_cast` is removed and `simd_cast` is changed to accept both scalable and non-scalable intrinsics, an approach that will scale better to the other intrinsics.

Building on the previous change, support scalable vectors with `simd_select`. Previous patches already landed the necessary changes in the implementation of this intrinsic, but didn't allow scalable vector arguments to be passed in.
2026-04-13 14:02:32 +02:00
Jonathan Brouwer
ab551b1550 Rollup merge of #155096 - aerooneqq:delegation-user-specified-args-impl-traits, r=petrochenkov
delegation: support proper interaction of user-specified args and impl Traits

This PR supports usages of user-specified args with impl Traits. When there are user-specified args in child we still need to generate synthetic generic params and use them during signature inheritance:
```rust
fn foo<T, const N: usize>(f: impl FnOnce()) {}

reuse foo::<String, 123> as bar;

//desugaring
fn bar<TSynth: impl FnOnce()>(f: _) {
    foo::<String, 123>(f)
}
```
When inheriting predicates we process impl Trait ones, so we need generic params to instantiate them. Other approach may involve not generating synthetic generic params and try to filter out those predicates, but fairly generating synthetic params seems more consistent?.

Fixes rust-lang/rust#154780, part of rust-lang/rust#118212.

r? @petrochenkov
2026-04-13 14:02:31 +02:00
Jonathan Brouwer
7370657c2b Rollup merge of #154932 - TaKO8Ki:fix-152887-rtn-assoc-type-name, r=jackh726
Handle RTN projections in assoc type restriction diagnostics

Fixes rust-lang/rust#152887
2026-04-13 14:02:31 +02:00
Jonathan Brouwer
d4037f7d8f Rollup merge of #153335 - Ozzy1423:removed-features, r=jdonszelmann
Add #![unstable_removed(..)] attribute to track removed features

Adds the #![unstable_removed(..)] attribute to enable tracking removed library features.
Produce an error when a removed attribute is used.
Add a test that it works.

For https://github.com/rust-lang/rust/issues/141617

r? @jyn514
2026-04-13 14:02:30 +02:00
Jonathan Brouwer
23c6bc9fe5 Rollup merge of #155227 - lnicola:sync-from-ra, r=lnicola
`rust-analyzer` subtree update

Subtree update of `rust-analyzer` to 7b6e1249b7.

Created using https://github.com/rust-lang/josh-sync.

r? @ghost
2026-04-13 14:02:29 +02:00
Folkert de Vries
6f428df8df preseve SIMD element type information
and provide it to LLVM for better optimization
2026-04-13 13:26:50 +02:00
Zalathar
316fcbd217 Check diagnostic output in incremental cpass and rpass revisions
This allows warnings to be annotated, and verifies that no unexpected warnings
occur.
2026-04-13 20:48:07 +10:00
Zalathar
8565c4a5de Extract check_compiler_output_for_incr 2026-04-13 20:48:07 +10:00
Zalathar
c79fcfcca8 Fix some irrelevant warnings in tests/incremental
This avoids having to add several unhelpful annotations when enabling
diagnostic checks for `cpass` and `rpass` revisions.
2026-04-13 20:48:07 +10:00
Jacob Adam
d14be60b5d Convert the regression test for a coroutine ICE from a crash test to an UI test 2026-04-13 11:45:07 +01:00
Jacob Adam
189305eda3 Skip the closure signature annotation check for tainted bodies
When a coroutine has too many parameters, `check_match` fails and
`construct_error` builds a MIR body with only the coroutine's computed
args (env + resume type). The user-provided signature, however, still
reflects all the parameters the user wrote. `check_signature_annotation`
then tries to `zip_eq` these two mismatched iterators, causing a panic.
Checking `tainted_by_errors` and bailing early avoids this, since
`construct_error` bodies cannot meaningfully be compared against user
annotations.
2026-04-13 11:45:07 +01:00
Arthur Carcano
b52a38dbf3 Add link to Unicode White_Space property 2026-04-13 11:47:54 +02:00
Chayim Refael Friedman
23e8460986 Merge pull request #22022 from ChayimFriedman2/restrictions
feat: Support `impl` and `mut` restrictions
2026-04-13 09:47:24 +00:00
Chayim Refael Friedman
1a77f3d7df Support impl and mut restrictions
I chose the order of mut restrictions to be `unsafe mut(...)` for unsafe fields, but it's undecided yet.
2026-04-13 12:38:17 +03:00
Takayuki Maeda
9339abb8f9 move tests to associated-type-bounds/return-type-notation 2026-04-13 18:05:07 +09:00
Takayuki Maeda
205dd6f50b reduce ICE reproducer 2026-04-13 18:05:07 +09:00
Takayuki Maeda
dbf8681242 handle RTN projections in assoc type restriction diagnostics 2026-04-13 18:05:07 +09:00
Takayuki Maeda
eb11900474 add regression test for RTN assoc type restriction ICE 2026-04-13 18:05:07 +09:00
Takayuki Maeda
af80b0f2cd do not lint doc_cfg as an unused feature 2026-04-13 17:21:17 +09:00
bendn
63f813ab2d spec next chunk for trustedlen 2026-04-13 15:08:04 +07:00
Laurențiu Nicola
3204a7960c Merge pull request #22025 from A4-Tacks/extract-fun-transparent-index
fix: no deref index-expr for extract_function
2026-04-13 07:57:58 +00:00
aerooneqq
51888a15fb Support proper interaction of user-specified args and impl Traits 2026-04-13 10:55:03 +03:00
aerooneqq
d283703bae Add tests for ICEs when hir_crate_items executed before delayed lowering 2026-04-13 10:26:17 +03:00
aerooneqq
791a3dcef0 Revert "Fix cycles during delayed lowering" 2026-04-13 10:19:33 +03:00
cijiugechu
e8858423a7 Add issue 155204 regression test 2026-04-13 14:28:03 +08:00
Redddy
c092fa7b49 Merge pull request rust-lang/rustc-dev-guide#2833 from rust-lang/tshepang-patch-1
show instead of explain
2026-04-13 14:43:07 +09:00
Tshepang Mbambo
c315ef2a1d show instead of explain
This should be clear with less words

r? @reddevilmidzy
2026-04-13 07:29:58 +02:00
Tshepang Mbambo
d7b595ca82 Merge pull request #2832 from rust-lang/rustc-pull
Rustc pull update
2026-04-13 07:24:29 +02:00
David Wood
a753cf4d77 core_arch: generated sve intrinsics
Following from previous commit, this commit only contains generated code
from the SVE intrinsic specifications

Co-authored-by: Jamie Cunliffe <Jamie.Cunliffe@arm.com>
Co-authored-by: Luca Vizzarro <Luca.Vizzarro@arm.com>
Co-authored-by: Adam Gemmell <adam.gemmell@arm.com>
Co-authored-by: Jacob Bramley <jacob.bramley@arm.com>
2026-04-13 05:19:16 +00:00
David Wood
ca5032f50f gen-arm: add sve intrinsic definitions
Thousands of lines of SVE intrinsic definitions..

Co-authored-by: Jamie Cunliffe <Jamie.Cunliffe@arm.com>
Co-authored-by: Luca Vizzarro <Luca.Vizzarro@arm.com>
Co-authored-by: Adam Gemmell <adam.gemmell@arm.com>
Co-authored-by: Jacob Bramley <jacob.bramley@arm.com>
2026-04-13 05:19:16 +00:00
David Wood
a7d4530a98 gen-arm: correct renamed from_exposed_addr link
`core::ptr::from_exposed_addr` was renamed to
`core::ptr::with_exposed_provenance` and so this link needs updated.
2026-04-13 05:19:16 +00:00
David Wood
78ccc92770 gen-arm: use sve_into instead of into
`Into::into` can't be used here because the implementations can't have
the required target feature, so `SveInto` needs to be introduced and
written by the generator
2026-04-13 05:19:16 +00:00
David Wood
826ab8ba0e core_arch: sve types
Add the SVE types (without any of the generated intrinsics) and empty
modules where the generated intrinsics will be. Enables the
`adt_const_params` crate feature that the generated intrinsics will use.

Co-authored-by: Jamie Cunliffe <Jamie.Cunliffe@arm.com>
Co-authored-by: Luca Vizzarro <Luca.Vizzarro@arm.com>
Co-authored-by: Adam Gemmell <adam.gemmell@arm.com>
Co-authored-by: Jacob Bramley <jacob.bramley@arm.com>
2026-04-13 05:19:16 +00:00
David Wood
2120148275 core_arch: add static_assert_range
This is a convenience macro used by the generated SVE intrinsics.

Co-authored-by: Jamie Cunliffe <Jamie.Cunliffe@arm.com>
Co-authored-by: Luca Vizzarro <Luca.Vizzarro@arm.com>
Co-authored-by: Adam Gemmell <adam.gemmell@arm.com>
Co-authored-by: Jacob Bramley <jacob.bramley@arm.com>
2026-04-13 05:19:16 +00:00
David Wood
c884079143 gen-arm: auto-llvm-sign-conversion not for into
Matching the current behaviour for arguments, `auto_llvm_sign_conversion`
should only be required for `as_unsigned` conversions, not `into`
conversions.
2026-04-13 05:19:16 +00:00
David Wood
55b65ff1ee gen-arm: s/simd_reinterpret/transmute_unchecked
`simd_reinterpret` was expected to be used when it was added as
`transmute_unchecked` requires `Sized`, but scalable vectors are now
`Sized` so `transmute_unchecked` can be used and `simd_reinterpret` was
not added in rust-lang/rust#143924.
2026-04-13 05:19:16 +00:00
David Wood
8077797d75 gen-arm: remove SvUndef
The `SvUndef` expression is no longer necessary as a
`core::intrinsics::scalable::sve_undef` intrinsic has been introduced
to produce an undefined SVE vector, used by `svundef*` intrinsics. Other
intrinsics that used `SvUndef` now use the `svundef*` intrinsics.
2026-04-13 05:19:16 +00:00
David Wood
2637e0806b gen-arm: add generate_load_store_tests
Instead of generating load/store tests based on the input filename -
which no longer works given the expected input file structure of
`stdarch-gen-arm` - add a simple global context option that SVE specs can
set.
2026-04-13 05:19:16 +00:00
David Wood
9f43e2a99f stdarch-verify: re-add runtime test check
This was accidentally removed in 713444d.
2026-04-13 05:19:16 +00:00
The rustc-josh-sync Cronjob Bot
401da2312a Merge ref '14196dbfa3eb' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@14196dbfa3
Filtered ref: rust-lang/rustc-dev-guide@9def1ed522
Upstream diff: 30d0309fa8...14196dbfa3

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-13 05:11:35 +00:00
The rustc-josh-sync Cronjob Bot
9ddab4d30b Prepare for merging from rust-lang/rust
This updates the rust-version file to 14196dbfa3.
2026-04-13 05:11:29 +00:00
cijiugechu
b7bd207d63 Avoid projection-only constraint suggestions for inherent associated type mismatches 2026-04-13 12:36:46 +08:00
David Wood
da948999eb cg_ssa: transmute between scalable vectors
Like regular SIMD vectors, we can support casting between scalable
vectors of integral or floating-point types without needing a temporary.
2026-04-13 04:24:28 +00:00
Redddy
5273a4c567 Merge pull request rust-lang/rustc-dev-guide#2831 from reddevilmidzy/bors-squash
Document quoting for `@bors squash msg=`
2026-04-13 11:53:51 +09:00
Redddy
269feca4ca Document quoting for @bors squash msg= 2026-04-13 11:39:17 +09:00
David Wood
62ffc89914 cg_llvm: scalable vectors with simd_select
Building on the previous change, support scalable vectors with
`simd_select`. Previous patches already landed the necessary changes in
the implementation of this intrinsic, but didn't allow scalable vector
arguments to be passed in.
2026-04-13 01:57:55 +00:00
David Wood
ca6a85155b cg_llvm: replace sve_cast with simd_cast
Previously `sve_cast`'s implementation was abstracted to power both
`sve_cast` and `simd_cast` which supported scalable and non-scalable
vectors respectively. In anticipation of having to do this for another
`simd_*` intrinsic, `sve_cast` is removed and `simd_cast` is changed to
accept both scalable and non-scalable intrinsics, an approach that will
scale better to the other intrinsics.
2026-04-13 01:57:55 +00:00
Jieyou Xu
67be8c2543 tidy: handle #[cfg_attr(bootstrap, doc = "...")] in compiler/ comments
For the unbalanced backtick check. This fix is arguably a hack, however
the original tidy check implementation is already based on heuristics
and so are likewise fuzzy. This is probably fine in practice.

Co-authored-by: Waffle Lapkin <waffle.lapkin@gmail.com>
2026-04-13 09:28:58 +08:00
Redddy
d928b2bbf7 Merge pull request rust-lang/rustc-dev-guide#2821 from apiraino/fix-notif-grp-links
Fix GPU target notification group links
2026-04-13 10:01:27 +09:00
mejrs
f468cef3db Format the duplicate macro 2026-04-13 00:02:09 +02:00
mejrs
0dd591aeab Delete unused AttributeLintKind variant 2026-04-12 23:42:10 +02:00
mejrs
217c073962 move list parsing into its own function 2026-04-12 23:24:44 +02:00
Jacob Adam
1bdbde5148 Move spdx.rs to spdx/mod.rs 2026-04-12 22:06:47 +01:00
Jacob Adam
57de72c2e2 Add a bunch of unit tests for the in-house parser 2026-04-12 22:06:47 +01:00
Jacob Adam
8712a92427 Replace the spdx-rs dependency with a minimal in-tree SPDX tag-value parser
The spdx-rs crate is no longer maintained and is behind on its own dependency
updates. The only function that collect-license-metadata uses from it is
`spdx_rs::parsers::spdx_from_tag_value`, which parses the output of the `reuse`
tool to extract file names, licences and copyright text.

Replace this with a small minimal parser that handles just the subset
of the SPDX tag-value format that is needed: `Tag: Value` line pairs
and multi-line `<text>...</text>` blocks.

Coincidentally, this gets rid of the last transitive dependency on syn v1.
2026-04-12 22:06:46 +01:00
A4-Tacks
67ed22e34e fix: no deref index-expr for extract_function
Example
---
```rust
fn foo() {
    let mut arr = [1i32];
    $0arr[0] = 3;$0
    let _ = arr;
}
```

**Before this PR**

```rust
fn foo() {
    let mut arr = [1i32];
    fun_name(&mut arr);
    let _ = arr;
}

fn $0fun_name(arr: &mut [i32; 1]) {
    *arr[0] = 3;
}
```

**After this PR**

```rust
fn foo() {
    let mut arr = [1i32];
    fun_name(&mut arr);
    let _ = arr;
}

fn $0fun_name(arr: &mut [i32; 1]) {
    arr[0] = 3;
}
```
2026-04-13 04:15:58 +08:00
BoxyUwU
84f4b803f7 Release notes for 1.95 2026-04-12 15:48:50 -04:00
mejrs
57fd9747fb Merge "missing options" lints for diagnostic attributes 2026-04-12 21:37:45 +02:00
Folkert de Vries
15c1e3479c Merge pull request #2080 from sayantn/sde-update
Update SDE to v10.8.0
2026-04-12 19:08:17 +00:00
sayantn
139f9648dd Update SDE to v10.8.0 2026-04-13 00:17:25 +05:30
mejrs
e9d0e320ec Merge malformed diagnostic attribute lint 2026-04-12 20:39:25 +02:00
sayantn
11f350da38 Add autocast for bf16 and bf16xN 2026-04-12 23:33:27 +05:30
sayantn
5aa800af80 Add autocast for i1 vectors 2026-04-12 23:33:27 +05:30
sayantn
3d89a5be50 Add autocasts for structs 2026-04-12 23:33:27 +05:30
sayantn
a5372be2a1 Add target arch verification for LLVM intrinsics 2026-04-12 23:33:27 +05:30
sayantn
c21f4ee437 Check for AutoUpgraded intrinsics, and lint on uses of deprecated intrinsics 2026-04-12 23:33:15 +05:30
Sayantan Chakraborty
0086450677 Merge pull request #2075 from heiher/loong64-tests-avoid-const-folding
loongarch: Avoid constant folding in tests to ensure SIMD coverage
2026-04-12 17:50:00 +00:00
bors
14196dbfa3 Auto merge of #154840 - Walnut356:windows_gdb_embed, r=mati865
allow `windows-gnu` targets to embed gdb visualizer scripts

Pretty straigthforward, works exactly the same as any other `*-gnu` target so i'm not sure why it wasn't enabled already.
2026-04-12 17:09:00 +00:00
mejrs
08a12dc143 Add feature hint for unstable diagnostic attributes 2026-04-12 18:38:17 +02:00
Ralf Jung
66dd5870be Merge pull request #4949 from michaliskok/genmc-no-nas
GenMC: Fixes and improved non-atomic handling
2026-04-12 16:18:03 +00:00
Ralf Jung
66cdfc411e tweak some comments 2026-04-12 17:52:35 +02:00
Michalis Kokologiannakis
4fe97684b4 genmc/build: Bump GenMC version 2026-04-12 17:27:12 +02:00
Michalis Kokologiannakis
75897f90b6 tests/genmc: Bless new results
The difference is caused by the different order in which GenMC
explores executions, and the new error-detection mechanism.
2026-04-12 17:27:12 +02:00
Michalis Kokologiannakis
7f7fdd4631 genmc/build: Don't add labels for non-atomics to graphs
Necessary for GenMC to build. Makes exploration much faster
since NAs are not explicitly tracked.
2026-04-12 17:27:12 +02:00
Michalis Kokologiannakis
a8685f739f genmc/build: ENABLE_GENMC_DEBUG is available in config.h 2026-04-12 17:27:12 +02:00
Michalis Kokologiannakis
8a3c8cbc75 genmc/lib: GENMC_DEBUG has been renamed to ENABLE_GENMC_DEBUG 2026-04-12 17:27:12 +02:00
Michalis Kokologiannakis
a428be2f56 genmc/setup: Don't use InterpreterCallbacks
GenMC no longer relies on interpreter callbacks. It collects
all information it needs for both exploration and error-reporting
dynamically.
2026-04-12 17:27:12 +02:00
Michalis Kokologiannakis
8ac00e55d5 genmc: Replace BUG_ON() w/ VERIFY()
BUG_ON() no longer exists in GenMC.
2026-04-12 17:27:12 +02:00
Michalis Kokologiannakis
d42fe7175a genmc/exploration: Add a FIXME for join 2026-04-12 17:27:12 +02:00
Michalis Kokologiannakis
142d79dea2 genmc/*: Update GenMC calls to match the new API for NAs
- Fixes API calls to existing GenMC functions, which now
  return the number by which event_count should be increased
  - Properly handles "Invalid" results (where applicable)
  - Introduces handle_non_atomic_{store,load} in Miri and
  ensures they call their GenMC counterparts.
  - Adds NA handlers in Miri's GenmcCtx, and renames the previous
  handle_{load,store} to handle_atomic_{load,store}.
  - Removes handle_load_reset_if_none, the only purpose of which
  was to decrease the event counter.
  - Removes dec_pos(), which is now also unnecessary.
2026-04-12 17:27:12 +02:00
Ayuse
6733ce938f Add --verbose-run-make-subprocess-output flag to suppress run-make output
Add a flag to control verbose subprocess output for run-make tests. When using --no-capture on panic=abort test suites like cg_clif, passing test output can flood the terminal. This flag (default true) lets users opt out via --verbose-run-make-subprocess-output=false.

Extract a private print_command_output helper in run-make-support to avoid inlining the output logic in handle_failed_output, ensuring failures always print regardless of the flag.
2026-04-12 16:25:34 +01:00
ujjwalVishwakarma2006
9de8c8cf94 Add issue links and blessed error files 2026-04-12 20:43:28 +05:30
ujjwalVishwakarma2006
c9bfc85d1e Move tests to appropriate subdirectories 2026-04-12 20:36:55 +05:30
rishi-techo-14
e4da93435e moved 2 tests to organized locations 2026-04-12 19:32:35 +05:30
bors
dab8d9d106 Auto merge of #155199 - JonathanBrouwer:rollup-OhWpGAc, r=JonathanBrouwer
Rollup of 5 pull requests

Successful merges:

 - rust-lang/rust#155197 (miri subtree update)
 - rust-lang/rust#154804 (Fix ICE when reporting host-effect errors for const Fn HRTBs in next trait solver)
 - rust-lang/rust#155014 (Hexagon: add scalar arch-version target features (v60-v79, audio))
 - rust-lang/rust#155068 (Fix ICE in `span_extend_prev_while` with multibyte characters)
 - rust-lang/rust#155161 (Use Vec::push_mut when adding a chunk to arenas)
2026-04-12 13:57:41 +00:00
Ralf Jung
0f3670295b Merge pull request #4938 from WhySoBad/network-socket-non-blocking
Add support for non-blocking TCP sockets and operations
2026-04-12 13:53:16 +00:00
Jonathan Brouwer
bf4d3851c6 Rollup merge of #155161 - saethlin:push_mut_saves, r=Kivooeo
Use Vec::push_mut when adding a chunk to arenas

This fixes https://github.com/rust-lang/rust/issues/155148, which may or may not be worth fixing on its own merits, but I think `Vec::push_mut` also makes the code nicer.
2026-04-12 15:44:20 +02:00
Jonathan Brouwer
2834b1654a Rollup merge of #155068 - lapla-cogito:multibyte_char, r=mati865
Fix ICE in `span_extend_prev_while` with multibyte characters

Fixes https://github.com/rust-lang/rust/issues/155037

The function assumed that the character found by `rfind` was always one byte wide, using a hardcoded `1` instead of `c.len_utf8()`. When a multibyte character appeared immediately before the span, this caused the resulting span to point into the middle of a UTF-8 sequence, triggering an assertion failure in `bytepos_to_file_charpos`.
2026-04-12 15:44:20 +02:00
Jonathan Brouwer
5daeaa9b3a Rollup merge of #155014 - androm3da:hexagon-scalar-target-features, r=mati865
Hexagon: add scalar arch-version target features (v60-v79, audio)

Add target features corresponding to Hexagon LLVM CPU generations to complement the existing HVX vector features. These are needed for gating scalar intrinsics by architecture version.

New features: audio, v60, v62, v65, v66, v67, v68, v69, v71, v73, v75, v79

Each version implies the previous (e.g. v68 implies v67 which implies v66, etc.), matching LLVM's ArchV60-ArchV79 subtarget features.

Also adds hexagon revisions to the feature-hierarchy test to verify the implied feature chains work correctly.
2026-04-12 15:44:19 +02:00
Jonathan Brouwer
b36833d634 Rollup merge of #154804 - cijiugechu:fix/host-effect-hrtb-ice, r=adwinwhite
Fix ICE when reporting host-effect errors for const Fn HRTBs in next trait solver

Avoid leaking bound vars into the diagnostic selection path for HRTB host-effect predicates.

Closes rust-lang/rust#151894 .
2026-04-12 15:44:18 +02:00
Jonathan Brouwer
fa6fedceba Rollup merge of #155197 - RalfJung:miri, r=RalfJung
miri subtree update

Subtree update of `miri` to 871d3d06c5.

Created using https://github.com/rust-lang/josh-sync.

r? @ghost
2026-04-12 15:44:18 +02:00
sayantn
aa1a5f8a93 Codegen non-overloaded LLVM intrinsics using their name 2026-04-12 19:00:17 +05:30
WhySoBad
ff96becdda feat: add accept4 with SOCK_NONBLOCK test 2026-04-12 15:28:07 +02:00
Ralf Jung
5e2c5b2f94 avoid duplicating read/write_all logic 2026-04-12 15:27:50 +02:00
WhySoBad
99ac0a76f6 Add shims for non-blocking sockets and non-blocking socket operations 2026-04-12 15:26:58 +02:00
John Kåre Alsaker
6442b48dee Add more robust handling of nested query cycles 2026-04-12 14:38:43 +02:00
Piotr Spieker
03306632ff Use the term struct-like variant instead of anonymous structs for struct-like enum variants
This closer follows the terminology used in the Rust Book and Reference.

[Rust Book](https://doc.rust-lang.org/stable/book/ch06-01-defining-an-enum.html#listing-6-2):
> named fields, like a struct

[Reference](https://doc.rust-lang.org/stable/reference/items/enumerations.html#r-items.enum.constructor):
> struct-like enum variant
2026-04-12 14:22:08 +02:00
lapla
7f096cff9d Fix wrong suggestion for println_empty_string with non-parenthesis delimiters 2026-04-12 20:47:54 +09:00
David Knaack
b26760f10c Fix manpage version replacement and use verbose version 2026-04-12 13:37:16 +02:00
Michalis Kokologiannakis
ca6e18493a diagnostics: End sentences with a period 2026-04-12 12:48:52 +02:00
Michalis Kokologiannakis
912e6e57af diagnostics,genmc*: Add type to signal execution abortion
In the newer GenMC version, two RMWs might read from the same
write during an exploration. In such a case, the exploration
has to be dropped so that an alternative one can be explored.

Miri did not provide a way to completely stop an execution
without throwing an error. This commit adds a new TerminationInfo
case in diagnostics that is used by GenMC to signal that an
execution should be aborted.

On the API side, a new result field is introduced.
2026-04-12 12:48:52 +02:00
Michalis Kokologiannakis
66330faf42 genmc/api: Add a MallocResult type
This commit adds a new result type for malloc (preparatory).
2026-04-12 12:48:52 +02:00
Michalis Kokologiannakis
535df2ed12 genmc/api: Add a curr_pos()
Another preparatory commit before API adjustment.
2026-04-12 12:48:52 +02:00
Michalis Kokologiannakis
e77d11dc94 genmc/exploration: Have {inc,dec}_pos take a count argument
The new parameter allows to step the event index by an arbitrary
amount. The functions now return void.

This is a preparatory commit that lays the ground before adjusting
all API calls to match the new GenMC API. The code does not
compile.
2026-04-12 12:48:52 +02:00
Michalis Kokologiannakis
80a207a102 genmc/*: Fix paths and naming for graph-related includes
The "ExecutionGraph" GenMC folder has been renamed to "Execution",
and there is a GenMC class named ExecutionState.

This commit adjust the include paths in some cpp files, and renames
an enum in lib.rs (ExecutionState->ExecutionStatus).
2026-04-12 12:48:52 +02:00
bors
532f8f1443 Auto merge of #155154 - clarfonthey:hashbrown-0.17, r=Mark-Simulacrum
Update hashbrown to 0.17

The main benefit of this update is to include one potential UB fix and one bug; relevant changelog entries:

* Fixed potential UB in `RawTableInner::fallible_with_capacity` (rust-lang/hashbrown#692)
* Fixed incorrect length if a hasher panics during rehash (rust-lang/hashbrown#710)

cc @Amanieu

Also cc @RalfJung who had also noticed the UB issue with `-Zmiri-recursive-validation`.
2026-04-12 10:44:20 +00:00
dswij
ea2b4d224f Fix unused_async FP for stubs with args (#16832)
Closes rust-lang/rust-clippy#16825

changelog: [`unused_async`] fix FP for stubs with args
2026-04-12 10:26:20 +00:00
Oscar Bray
25a92d208d Add #![unstable_removed(..)] attribute to track removed features
Move concat_idents to use the unstable_removed attribute
2026-04-12 11:18:10 +01:00
Jonathan Brouwer
106b16cd2d Add support for static EIIs in late resolution 2026-04-12 11:06:40 +02:00
Ralf Jung
edf04e18af Merge pull request #4950 from WhySoBad/fix-blocking-io-manager
Fix panic when multiple threads block on same fd
2026-04-12 09:04:53 +00:00
Sebastian Urban
b5ddfd5be4 Fix thread::available_parallelism on WASI targets
The refactoring in ba462864f1 ("std: Use more unix.rs code on WASI
targets") moved WASI from its own thread module into the shared unix.rs
module. However, it did not carry over the available_parallelism()
implementation for WASI, causing it to fall through to the unsupported
catch-all. This silently regressed the support originally added in
f0b7008648.

Fix this by adding WASI to the sysconf-based cfg_select arm alongside
other platforms that use libc::sysconf(_SC_NPROCESSORS_ONLN). This
delegates to wasi-libc, which currently always returns 1 but opens up
the possibility for wasi-libc to report actual processor counts in the
future.

This requires libc to export _SC_NPROCESSORS_ONLN for WASI targets,
which has been added in libc 0.2.184.
2026-04-12 09:52:47 +02:00
Lukas Wirth
c0ad60428b Merge pull request #22009 from A4-Tacks/no-expr-in-qualified
fix: no complete term expressions on qualified path
2026-04-12 07:37:10 +00:00
Lukas Wirth
8865266c4e Merge pull request #22012 from A4-Tacks/no-import-on-type-anchor-qualifier
fix: no imports on type anchor qualified path
2026-04-12 07:37:06 +00:00
bors
540f43a224 Auto merge of #155185 - matthiaskrgr:rollup-JYNqFhW, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - rust-lang/rust#155171 (Patch musl's CVE-2026-6042 and CVE-2026-40200)
 - rust-lang/rust#153630 (Deprioritize doc(hidden) re-exports in diagnostic paths)
 - rust-lang/rust#152613 (unsafe keyword docs: bring back unsafe_op_in_unsafe_fn lint discussion)
 - rust-lang/rust#155142 (impl const Residual for ControlFlow)
2026-04-12 07:34:56 +00:00
ArshLabs
dc36b8e3c2 std: fix HashMap RNG docs wording 2026-04-12 12:34:29 +05:30
cijiugechu
0b02f678c4 Handle leaked host-effect HRTBs before selection 2026-04-12 14:44:20 +08:00
Matthias Krüger
11469dc9f5 Rollup merge of #155142 - nxsaken:const_residual_control_flow, r=fee1-dead
impl const Residual for ControlFlow

Feature: rust-lang/rust#91285 (`try_trait_v2_residual`/`const_try_residual`)

r? @fee1-dead
2026-04-12 08:15:48 +02:00
Matthias Krüger
ba98b3558a Rollup merge of #152613 - RalfJung:unsafe-keyword-docs, r=traviscross
unsafe keyword docs: bring back unsafe_op_in_unsafe_fn lint discussion

@traviscross in rust-lang/rust#141471 you asked me to also update the text to account for the edition change. Apparently I did that by entirely removing this part of the discussion (except for a dangling forward reference, a "see below"). Given that old editions still exist and given that `unsafe_op_in_unsafe_fn` is just a lint so the old behavior also still exists on new editions, I am no longer sure that was a good idea, so this brings back the old text with some editing to explain the current situation.
2026-04-12 08:15:47 +02:00
Matthias Krüger
56ecb157e2 Rollup merge of #153630 - arferreira:fix-doc-hidden-reexport-diagnostic-path, r=jackh726
Deprioritize doc(hidden) re-exports in diagnostic paths

Fixes rust-lang/rust#153477.

This is the other half of rust-lang/rust#99698, which fixed the case where the *parent module* is `#[doc(hidden)]` but left the case where the re-export itself is `#[doc(hidden)]` as a FIXME (with a tracking test in `dont-suggest-doc-hidden-variant-for-enum/hidden-child.rs`).

The problem: when a crate does `#[doc(hidden)] pub use core::error::Error`, diagnostics pick up the hidden re-export path instead of the canonical one. For example, `snafu::Error` instead of `std::error::Error`.

Two changes:

In `visible_parent_map`, the `add_child` closure now checks whether the re-export itself is `#[doc(hidden)]` via `reexport_chain` and sends it to `fallback_map`, same treatment as doc-hidden parents and underscore re-exports.

`should_encode_attrs` now returns `true` for `DefKind::Use`. Without this, `#[doc(hidden)]` on `use` items was never written to crate metadata, so `is_doc_hidden` always returned `false` cross-crate. This was the actual root cause, the check in `visible_parent_map` alone isn't enough if the attribute isn't in the metadata.

The existing FIXME test now serves as the regression test. The `.stderr` goes from suggesting `hidden_child::__private::Some(1i32)` to just `Some(1i32)`.

cc @eggyal
2026-04-12 08:15:46 +02:00
Matthias Krüger
8bd29964c0 Rollup merge of #155171 - cuviper:musl-cves, r=Mark-Simulacrum
Patch musl's CVE-2026-6042 and CVE-2026-40200

- [CVE-2026-6042] is a denial of service in `iconv`.
- [CVE-2026-40200] is an out-of-bounds write in `qsort`.

Neither is relevant to Rust itself, but they could be used in mixed-language projects that link with our `self-contained/libc.a`.

[CVE-2026-6042]: https://www.openwall.com/lists/oss-security/2026/04/09/19
[CVE-2026-40200]: https://www.openwall.com/lists/musl/2026/04/10/3
2026-04-12 08:15:46 +02:00
bors
d32e620a10 Auto merge of #155166 - JonathanBrouwer:rollup-YH2oUIz, r=JonathanBrouwer
Rollup of 6 pull requests

Successful merges:

 - rust-lang/rust#155057 (Update libc to v0.2.184)
 - rust-lang/rust#154967 (Test(lib/sync): Fix `test_rwlock_max_readers` for x86 Win7)
 - rust-lang/rust#154994 (don't leak internal temporaries from `dbg!`)
 - rust-lang/rust#155130 (Stabilize feature `isolate_most_least_significant_one`)
 - rust-lang/rust#154925 (Make Box/Rc/Arc::into_array allocator-aware (and add doctest))
 - rust-lang/rust#155063 (`ty::Alias`: replace `def_id: did` with `def_id`)
2026-04-12 04:25:51 +00:00
Travis Cross
ae3b150378 Fix a typo 2026-04-12 04:03:30 +00:00
Daniel Scherzer
d72b0e73a4 implementing-new-features.md: update parameters to declare_features!
The edition parameter was removed
2026-04-11 19:06:05 -07:00
León Orell Valerian Liehr
fc2c72cb67 Make the expansion of guard metavars begin guard non-terminals 2026-04-12 03:18:56 +02:00
bors
6ad4d1b0e7 Auto merge of #155175 - jhpratt:rollup-jQuvnVx, r=jhpratt
Rollup of 7 pull requests

Successful merges:

 - rust-lang/rust#155084 (Initial functions to start on transmute v2)
 - rust-lang/rust#155126 (add `cfg(target_object_format = "...")`)
 - rust-lang/rust#155165 (Portable SIMD subtree update)
 - rust-lang/rust#153871 (fix spurious test failure in `metadata_access_times`)
 - rust-lang/rust#155150 (replace <name> @ ty::AliasTy matches with just using args: <name>_args)
 - rust-lang/rust#155159 (Fix min-specialization ICE from ignored region resolution failure)
 - rust-lang/rust#155167 (Reduce size of `ImportData`)
2026-04-12 01:16:28 +00:00
Jacob Pratt
040b6db55d Rollup merge of #155167 - mejrs:box_directive, r=Kivooeo
Reduce size of `ImportData`

Perhaps this will undo the regression caused by https://github.com/rust-lang/rust/pull/152901
2026-04-11 21:12:23 -04:00
Jacob Pratt
22328dc33a Rollup merge of #155159 - TaKO8Ki:min-specialization-next-solver-region-resolution, r=Kivooeo
Fix min-specialization ICE from ignored region resolution failure

Fixes rust-lang/rust#151327

`min_specialization::get_impl_args` resolved regions and then immediately called `fully_resolve`, but it ignored failures from `resolve_regions_and_report_errors`.

Propagate the region-resolution error instead of ignoring it. That matches the pattern used in:

40a3ed1e14/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs (L706)

40a3ed1e14/compiler/rustc_hir_analysis/src/coherence/builtin.rs (L421)
2026-04-11 21:12:23 -04:00
Jacob Pratt
6d7015ccab Rollup merge of #155150 - WilliamTakeshi:alias-ty-args-binding, r=WaffleLapkin,Kivooeo
replace <name> @ ty::AliasTy matches with just using args: <name>_args

ref rust-lang/rust#154941

replace `<name> @ ty::AliasTy` matches with just using `args: <name>_args`

I updated all occurrences where <name> @ ty::AliasTy became unnecessary after the change. In cases where both forms are still used, no changes were made.

r? @WaffleLapkin
2026-04-11 21:12:22 -04:00
Jacob Pratt
af4f14bd3d Rollup merge of #153871 - mattiapitossi:issue-148408, r=Mark-Simulacrum
fix spurious test failure in `metadata_access_times`

Fixes rust-lang/rust#148408

The metadata_access_times test checks if the creation of a file occurs before another file, this check happens only on Linux. While on Win and Macos we check only that the created metadata is available. Given that the SystemTime is non monotonic as Instant this test could result in failures when the system clock changes.
2026-04-11 21:12:22 -04:00
Jacob Pratt
d82e5e6bde Rollup merge of #155165 - folkertdev:sync-from-portable-simd-2026-04-11, r=folkertdev
Portable SIMD subtree update

Let's see if this works (we might need a sync the other way first)
2026-04-11 21:12:21 -04:00
Jacob Pratt
1700a21d10 Rollup merge of #155126 - folkertdev:target-object-format, r=Urgau
add `cfg(target_object_format = "...")`

tracking issue: https://github.com/rust-lang/rust/issues/152586

I'm implementing the predicate as `target_object_format`, because that's what is useful to me (for testing `#[link_section = "..."]` where `mach-o` has some extra restrictions) and maps cleanly to the `BinaryFormat` enum that is used internally. There is still room for a future `target_executable_format` when there is a use case.

cc @joshtriplett as the lang sponsor of this feature, @workingjubilee as the author of the proposal.

r? JonathanBrouwer a sidequest from the sidequest that is https://github.com/rust-lang/rust/pull/155065
2026-04-11 21:12:20 -04:00
Jacob Pratt
d83352b491 Rollup merge of #155084 - scottmcm:add-transmute-prefix, r=Mark-Simulacrum
Initial functions to start on transmute v2

For context, see https://github.com/rust-lang/rfcs/pull/3844 and https://github.com/rust-lang/libs-team/issues/772

*Experimental* still, tracked under https://github.com/rust-lang/rust/issues/155079

This is just library functions.  A future PR will do compiler changes for things like lints.
2026-04-11 21:12:19 -04:00
LemonJ
c6befd82ce fix: add aliasing rules for Box 2026-04-12 09:07:07 +08:00
workflows-rust-analyzer[bot]
5ff216c7db internal: update generated lints 2026-04-12 00:00:25 +00:00
mejrs
55cd47658c Change edit distance to not suggest on_move and on_const against each other 2026-04-12 01:47:07 +02:00
mejrs
d69403abfc Properly emit diagnostic for diagnostic::on_move being used without feature gate 2026-04-12 01:42:04 +02:00
mejrs
21925e9e23 Lazily check diagnostic namespace features 2026-04-12 01:24:04 +02:00
jackh726
a4c494472b A couple small comment cleanups, and update tests. 2026-04-11 22:54:47 +00:00
Josh Stone
88305519bb Patch musl's CVE-2026-6042 and CVE-2026-40200
- [CVE-2026-6042] is a denial of service in `iconv`.
- [CVE-2026-40200] is an out-of-bounds write in `qsort`.

Neither is relevant to Rust itself, but they could be used in mixed-
language projects that link with our `self-contained/libc.a`.

[CVE-2026-6042]: https://www.openwall.com/lists/oss-security/2026/04/09/19
[CVE-2026-40200]: https://www.openwall.com/lists/musl/2026/04/10/3
2026-04-11 15:25:37 -07:00
Chayim Refael Friedman
1b81c1d3f9 Merge pull request #21965 from ChayimFriedman2/refactor-cfg-attr
fix: Parse `cfg_attr` and `cfg` specially
2026-04-11 20:25:46 +00:00
Chayim Refael Friedman
671b6606c2 Parse cfg_attr and cfg specially
This allows us to simplify expansion of cfg_attr in `expand_cfg_attr()`, and also fixes a bunch of bugs like expansion of `doc = macro!()` inside `cfg_attr`.
2026-04-11 23:15:10 +03:00
mejrs
c4e4156037 Reduce size of ImportData 2026-04-11 21:14:45 +02:00
Jonathan Brouwer
58ca4df0bd Rollup merge of #155063 - josetorrs:refactor-alias-free, r=WaffleLapkin
`ty::Alias`: replace `def_id: did` with `def_id`

related issue: https://github.com/rust-lang/rust/issues/154941

tackling this task:

- [x] replace def_id: did with def_id where possible

r? @WaffleLapkin
2026-04-11 20:58:37 +02:00
Jonathan Brouwer
9a24dbf885 Rollup merge of #154925 - zachs18:heap-into-array-with-alloc, r=Mark-Simulacrum
Make Box/Rc/Arc::into_array allocator-aware (and add doctest)

Tracking issue for `alloc_slice_into_array`: https://github.com/rust-lang/rust/issues/148082

Tracking issue for `allocator_api`: https://github.com/rust-lang/rust/issues/32838

Make the `into_array` methods on `Box`, `Rc`, and `Arc` allocator-aware.

I think the allocator-aware-ness should not be observable on stable, so these should not be additionally (comment-)gated behind `feature(allocator_api)`, just like e.g. `Box::leak` and `Vec::into_boxed_slice`. The added doctests do not use `feature(allocator_api)`.

@rustbot label T-libs-api
2026-04-11 20:58:37 +02:00
Jonathan Brouwer
73a3824826 Rollup merge of #155130 - okaneco:stabilize_iso_high_one, r=Mark-Simulacrum
Stabilize feature `isolate_most_least_significant_one`

FCP completed https://github.com/rust-lang/rust/issues/136909#issuecomment-4224884128

Closes https://github.com/rust-lang/rust/issues/136909
2026-04-11 20:58:36 +02:00
Jonathan Brouwer
59b36a5283 Rollup merge of #154994 - dianne:no-dbg-temp, r=Mark-Simulacrum
don't leak internal temporaries from `dbg!`

Fixes rust-lang/rust#154988

r? @Mark-Simulacrum as the reviewer of https://github.com/rust-lang/rust/pull/154074
2026-04-11 20:58:35 +02:00
Jonathan Brouwer
197eb8c6c0 Rollup merge of #154967 - PaulDance:patches/fix-x86-win7-rwlock-max-test, r=Mark-Simulacrum
Test(lib/sync): Fix `test_rwlock_max_readers` for x86 Win7

The test recently added in rust-lang/rust#153555 currently systematically deadlocks when running it under i686 Windows 7, but not x86_64 that passes it fine. This therefore fixes the test for the target.

Empirically, the correct value for `MAX_READERS` seems to be `2^28 - 1`: removing the `- 1` re-introduces the deadlock, at least under our testing environment. This fix thus uses this value. However, I have no real justification to support that, because I find myself a bit at a loss when comparing the implementation details, the comment added above the test and what the current value is; some help would therefore be nice in this aspect. Also, the value change is restricted to 32-bit Win7 as there is no evidence to support it should be done for other targets.

cc @roblabla

@rustbot label O-windows-msvc O-windows-7 O-x86_32 A-atomic T-libs
2026-04-11 20:58:35 +02:00
Jonathan Brouwer
81578ef0c9 Rollup merge of #155057 - rust-wasi-web:update-libc-0.2.184, r=Mark-Simulacrum
Update libc to v0.2.184

This includes the WASI _SC_* sysconf constants needed for `thread::available_parallelism` on WASI targets (rust-lang/rust#153604).
2026-04-11 20:58:34 +02:00
Folkert de Vries
aa656a91df Merge commit '0557e3478104037c76c2e5be7ea21e56ebbaff6e' into sync-from-portable-simd-2026-04-11 2026-04-11 20:28:28 +02:00
WilliamTakeshi
a133bb8f27 replace @ ty::AliasTy matches with just args 2026-04-11 18:00:32 +00:00
Jose Torres
ec582d5c1b replace def_id: did with def_id 2026-04-11 13:59:31 -04:00
A4-Tacks
cb666a0e68 fix: enable vscode suggest in strings
Co-authored-by: Amit Singhmar <abhay.singhmar2@gmail.com>
2026-04-12 01:50:12 +08:00
Ben Kimock
ff6191588a Use Vec::push_mut when adding a chunk to arenas 2026-04-11 12:58:21 -04:00
Vastargazing
f9b6718308 add regression test for OpenOptionsExt downstream compat 2026-04-11 19:58:04 +03:00
Jules Bertholet
cd061c73af Extend core::char's documentation of casing issues
* Extend `core::char`'s documentation of casing issues
* Fix typos
* Fix typo

Co-authored-by: GrigorenkoPV <GrigorenkoPV+github@yandex.ru>
* Document maximum 3x character expansion

This is guaranteed by Unicode.
* Fix error in `str` casing method docs
2026-04-11 15:19:20 +00:00
Folkert de Vries
0557e34781 Add f16 vector support (#513)
* Add `f16` vector support

* run `cargo update`

* disable `f16` tests on wasm32 with simd128

llvm hangs in that case, see https://github.com/llvm/llvm-project/issues/189251

* Add reference to LLVM issue causing f16 wasm ICE

---------

Co-authored-by: Caleb Zulawski <caleb.zulawski@gmail.com>
2026-04-11 11:13:30 -04:00
WANG Rui
c43636ea4b loongarch: Avoid constant folding in tests to ensure SIMD coverage
Use `black_box` on SIMD intrinsic inputs to prevent the compiler from
constant folding SIMD operations, ensuring the corresponding SIMD
instructions are actually emitted and covered by tests.
2026-04-11 23:10:36 +08:00
Takayuki Maeda
40a3ed1e14 propagate region resolution failures 2026-04-12 00:03:46 +09:00
Takayuki Maeda
8998c11244 add next-solver min-specialization region-resolution regression test 2026-04-12 00:03:26 +09:00
Lukas Wirth
198e4c46a2 Merge pull request #22010 from erfanio/rustfmt-fix
Fix rustfmt relative custom command
2026-04-11 14:39:21 +00:00
Mattia Pitossi
9371fea6e6 fix spurious test failure in metadata_access_times
* remove time assertion on SystemTime
* skip test only if when a time change occurs
2026-04-11 14:31:53 +00:00
ltdk
32d6c7fd60 Update hashbrown to 0.17 2026-04-11 10:00:32 -04:00
bors
bf4fbfb7a1 Auto merge of #155149 - danieljofficial:move-tests-deref, r=Kivooeo
Move deref tests from issues into deref folder

Hi, Some deref tests, please look at them when you can
 r? @Kivooeo
2026-04-11 13:43:17 +00:00
Sayantan Chakraborty
7bd98dd3c1 Merge pull request #2073 from folkertdev/more-miri-tests
Test `vld4` with miri
2026-04-11 12:51:16 +00:00
Aliaksei Semianiuk
787dd491fa Changelog for Clippy 1.95 2026-04-11 17:27:11 +05:00
Folkert de Vries
6bcd172f5a add cfg(target_object_format = "...") 2026-04-11 14:12:39 +02:00
Samuel Tardieu
33a3b2223f Do not trigger let_and_return on let else 2026-04-11 13:53:28 +02:00
Ariel Ben-Yehuda
8864a6635b try to fix msvc 2026-04-11 14:15:15 +03:00
danieljofficial
cf986478fd add issue links and bless 2026-04-11 12:01:46 +01:00
Ada Alakbarova
08fa871dcc Even more fixes for handling of macros (#16443)
*[View all
comments](https://triagebot.infra.rust-lang.org/gh-comments/rust-lang/rust-clippy/pull/16443)*

Continuation rust-lang/rust-clippy#16337

Even more fixes for handling macros

changelog: [`manual_rotate`] fix wrongly unmangled macros
changelog: [`map_with_unused_argument_over_ranges`] fix wrongly
unmangled macros
changelog: [`needless_bool`] fix wrongly unmangled macros
changelog: [`manual_is_power_of_two`] fix wrongly unmangled macros
changelog: [`manual_div_ceil`] fix wrongly unmangled macros
changelog: [`implicit_saturating_sub`] fix wrongly unmangled macros
changelog: [`range_minus_one`] fix wrongly unmangled macros
changelog: [`range_plus_one`] fix wrongly unmangled macros
changelog: [`manual_swap`] fix wrongly unmangled macros
changelog: [`let_and_return`] fix wrongly unmangled macros
2026-04-11 10:53:58 +00:00
Shun Sakai
63b5ab2994 Stabilize feature int_lowest_highest_one 2026-04-11 18:38:21 +09:00
Ada Alakbarova
d588ba3068 Extend manual_filter to cover and_then (#16456)
*[View all
comments](https://triagebot.infra.rust-lang.org/gh-comments/rust-lang/rust-clippy/pull/16456)*

Closes rust-lang/rust-clippy#14440

Implemented as enhancement to `manual_filter`

changelog: [`manual_filter`] enhance to cover `and_then`
2026-04-11 09:34:11 +00:00
danieljofficial
c00aa3de46 move deref tests out of tests/ui/issues 2026-04-11 10:23:58 +01:00
bors
5f36a7f807 Auto merge of #155145 - jhpratt:rollup-atReM8h, r=jhpratt
Rollup of 3 pull requests

Successful merges:

 - rust-lang/rust#154827 (distinguish "expected a single argument" and "expected an argument" on attribute parsing)
 - rust-lang/rust#155104 (bootstrap: auto-patch libgccjit.so for NixOS)
 - rust-lang/rust#155120 (Use a linting node closer the parsing of `#[cfg_attr]`)
2026-04-11 09:03:13 +00:00
Jacob Pratt
b2088a21df Rollup merge of #155120 - Urgau:check-cfg-allow-cfg_attr-mod, r=JonathanBrouwer
Use a linting node closer the parsing of `#[cfg_attr]`

The parsing of `#[cfg_attr]` unconditionally used the crate-root as a linting node to attach lints, but the `unexpected_cfgs` lint can fire when parsing the attribute and users expect to be able to allow it at places other than the crate-root.

Let's instead use the linting node id, which is unfortunately always the parent but that's better than the crate-root when you are in a sub-module.

The parsing of `#[cfg]` and other already use the expansion linting node id, so no change required there.

Related to https://github.com/rust-lang/rust/issues/155118
2026-04-11 04:50:17 -04:00
Jacob Pratt
38ea36790f Rollup merge of #155104 - nbdd0121:bootstrap-gcc, r=Kobzol
bootstrap: auto-patch libgccjit.so for NixOS

Currently all downloaded rustc and LLVM components are auto patched on NixOS, but this is not done for libgccjit.so, so when GCC backend is enabled on NixOS, the build ICEs with errors like this:

    thread 'rustc' (2286205) panicked at compiler/rustc_codegen_gcc/src/lib.rs:191:9:
    Cannot load libgccjit.so: libzstd.so.1: cannot open shared object file: No such file or directory

Fix this by auto-patch libgccjit.so, too. `zstd` is added to the dependency environment.
2026-04-11 04:50:16 -04:00
Jacob Pratt
ca34f771c0 Rollup merge of #154827 - scrabsha:push-zuosxmmnzkrq, r=jdonszelmann
distinguish "expected a single argument" and "expected an argument" on attribute parsing
2026-04-11 04:50:15 -04:00
Jonathan Brouwer
1f2b0900a7 Reject multiple EII implementations on one static 2026-04-11 10:17:44 +02:00
Jonathan Brouwer
59ed245945 Reject mutable externally implementable statics 2026-04-11 10:17:44 +02:00
Jonathan Brouwer
fca29ada74 Uitests for external statics 2026-04-11 10:17:44 +02:00
Jonathan Brouwer
c7e194f215 Fix codegen for add_static_aliases 2026-04-11 10:17:44 +02:00
Jonathan Brouwer
607b0620e2 Analysis for externally implementable statics 2026-04-11 10:17:42 +02:00
Jonathan Brouwer
f1482364b6 Add eii_impls argument to StaticItem 2026-04-11 10:17:07 +02:00
Jonathan Brouwer
e756d1607d Add eii_impls argument to StaticItem 2026-04-11 10:17:07 +02:00
nxsaken
af2558094c impl const Residual for ControlFlow 2026-04-11 11:36:54 +04:00
bors
c29effdf79 Auto merge of #155141 - jhpratt:rollup-pjDewx9, r=jhpratt
Rollup of 3 pull requests

Successful merges:

 - rust-lang/rust#154661 (Semantic checks of `impl` restrictions)
 - rust-lang/rust#155132 (Suggest similar target names on unrecognized `--target`)
 - rust-lang/rust#155136 (Tweak comment about intrinsics in cross-crate-inlinable)
2026-04-11 05:49:32 +00:00
Jacob Pratt
bb745253f5 Rollup merge of #155136 - saethlin:intrinsic-cci-comment, r=wesleywiser
Tweak comment about intrinsics in cross-crate-inlinable

@RalfJung pointed out that the previous comment is technically wrong: https://github.com/rust-lang/rust/pull/145910#discussion_r2971285252
2026-04-11 01:49:13 -04:00
Jacob Pratt
9237f14282 Rollup merge of #155132 - jakedrew:fix/suggest-similar-target-on-unrecognized-155085, r=Kivooeo
Suggest similar target names on unrecognized `--target`

When an unrecognized `--target` is passed check the list of available targets and suggest the closest matching built-in target as a help message.

### Before

```
    error: error loading target specification: could not find specification for target "x86_64-linux-gnu"
      = help: run `rustc --print target-list` for a list of built-in targets
```

### After

```
    error: error loading target specification: could not find specification for target "x86_64-linux-gnu"
      = help: run `rustc --print target-list` for a list of built-in targets
      = help: did you mean `x86_64-unknown-linux-gnu`?
```

Regarding the expected test case in https://github.com/rust-lang/rust/issues/155085#issuecomment-4222050023 the `edit_distance_with_substrings` was used over `edit_distance` because in the case of `x86_64-linux-gnu` the `edit_distance` would return `x86_64-linux-android` instead of `x86_64-unknown-linux-gnu`

rust-lang/rust#155085
2026-04-11 01:49:13 -04:00
Jacob Pratt
fb16ce7254 Rollup merge of #154661 - CoCo-Japan-pan:impl-restriction-check, r=jhpratt,Urgau
Semantic checks of `impl` restrictions

This PR implements semantic checks for `impl` restrictions proposed in the [Restrictions RFC](https://rust-lang.github.io/rfcs/3323-restrictions.html) (Tracking Issue rust-lang/rust#105077), and linked to a [GSOC idea/proposal](142433eb3b (implementing-impl-and-mut-restrictions)).

It lowers the resolved paths of `impl` restrictions from the AST to HIR and into `TraitDef`, and integrates the checks into the coherence phase by extending `check_impl`. As parsing (rust-lang/rust#152943) and path resolution (rust-lang/rust#153556) have already been implemented, this PR provides a working implementation of `impl` restrictions.

r? @Urgau
cc @jhpratt
2026-04-11 01:49:12 -04:00
Jacob Pratt
44bad026ce Rollup merge of #154661 - CoCo-Japan-pan:impl-restriction-check, r=jhpratt,Urgau
Semantic checks of `impl` restrictions

This PR implements semantic checks for `impl` restrictions proposed in the [Restrictions RFC](https://rust-lang.github.io/rfcs/3323-restrictions.html) (Tracking Issue rust-lang/rust#105077), and linked to a [GSOC idea/proposal](142433eb3b (implementing-impl-and-mut-restrictions)).

It lowers the resolved paths of `impl` restrictions from the AST to HIR and into `TraitDef`, and integrates the checks into the coherence phase by extending `check_impl`. As parsing (rust-lang/rust#152943) and path resolution (rust-lang/rust#153556) have already been implemented, this PR provides a working implementation of `impl` restrictions.

r? @Urgau
cc @jhpratt
2026-04-11 01:49:12 -04:00
Young-Flash
67fa3a112c internal: auto exclude 2026-04-11 13:28:08 +08:00
Young-Flash
190557aac7 test: add test case for exclude refs from deps and stdlib 2026-04-11 13:23:48 +08:00
Young-Flash
f18e47485b fix: exclude declartion 2026-04-11 13:23:12 +08:00
Young-Flash
940c67f5b8 feat: exclude refs from deps and stdlib 2026-04-11 13:23:12 +08:00
Ben Kimock
270ebfcdf5 Tweak comment about intrinsics in cross-crate-inlinable 2026-04-10 22:42:12 -04:00
Zalathar
4a5c24f3cb Move the recursive step out of prefix_slice_suffix 2026-04-11 12:20:57 +10:00
Zalathar
80bb81359b Inline field_match_pairs into its callers 2026-04-11 11:53:05 +10:00
bors
c7c14d4fb0 Auto merge of #155044 - WaffleLapkin:dont-remove-unneeded-drops, r=scottmcm
Don't try to remove `drop_in_place` calls in `RemoveUnneededDrops`



As per my justification in https://github.com/rust-lang/rust/pull/154327#discussion_r3056946688

r? scottmcm
2026-04-11 00:55:22 +00:00
Josh Stone
20c9f54404 Document precision considerations of Duration-float methods
A `Duration` is essentially a 94-bit value (64-bit sec and ~30-bit ns),
so there's some inherent loss when converting to floating-point for
`mul_f64` and `div_f64`. We could go to greater lengths to compute these
with more accuracy, like rust-lang/rust#150933 or rust-lang/rust#154107,
but it's not clear that it's worth the effort. The least we can do is
document that some rounding is to be expected, which this commit does
with simple examples that only multiply or divide by `1.0`.

This also changes the `f32` methods to just forward to `f64`, so we keep
more of that duration precision, as the range is otherwise much more
limited there.
2026-04-10 16:25:55 -07:00
Shun Sakai
fe309a0bed Stabilize feature uint_bit_width 2026-04-11 07:46:34 +09:00
okaneco
a69f989fe1 Stabilize feature isolate_most_least_significant_one 2026-04-10 17:59:02 -04:00
Jake Drew
1137762b09 Suggest similar target names on unrecognized --target 2026-04-10 22:47:09 +01:00
bors
d1d3ef45a6 Auto merge of #155105 - Mark-Simulacrum:bump-release, r=Mark-Simulacrum
Bump to 1.97.0 release

https://forge.rust-lang.org/release/process.html#bump-the-stable-version-number-friday-the-week-before

r? me
2026-04-10 21:31:42 +00:00
WhySoBad
6d4d7a6daa fix: deregister I/O sources in blocking I/O manager 2026-04-10 23:19:58 +02:00
Folkert de Vries
cc1e6d8f51 Merge pull request #2076 from eduardosm/Simd-new
Remove `simd_ty!` and `simd_m_ty!` macros
2026-04-10 21:18:21 +00:00
WhySoBad
0b7f2254be fix: implement feedback 2026-04-10 21:06:22 +02:00
Eduardo Sánchez Muñoz
4103f7ddce Do not use a macro to define Simd::new 2026-04-10 20:42:25 +02:00
bors
c482441c1c Auto merge of #155115 - JonathanBrouwer:rollup-RePrRPQ, r=JonathanBrouwer
Rollup of 6 pull requests

Successful merges:

 - rust-lang/rust#152901 (Introduce a `#[diagnostic::on_unknown]` attribute)
 - rust-lang/rust#155078 (Reject dangling attributes in where clauses)
 - rust-lang/rust#154449 (Invert dependency between `rustc_errors` and `rustc_abi`.)
 - rust-lang/rust#154646 (Add suggestion to `.to_owned()` used on `Cow` when borrowing)
 - rust-lang/rust#154993 (compiletest: pass -Zunstable-options for unpretty and no-codegen paths)
 - rust-lang/rust#155097 (Make `rustc_attr_parsing::SharedContext::emit_lint` take a `MultiSpan` instead of a `Span`)
2026-04-10 18:19:03 +00:00
Eduardo Sánchez Muñoz
8d85d1def7 Do not use SimdM::new and remove simd_m_ty! 2026-04-10 20:12:46 +02:00
Urgau
f97143d951 Use a linting node closer the parsing of #[cfg_attr] 2026-04-10 20:04:37 +02:00
Laurențiu Nicola
79758acd6e Merge pull request #21998 from rust-lang/ci/gen-lints
Update generated lints
2026-04-10 17:49:21 +00:00
Jonathan Brouwer
32213c6635 Rollup merge of #154646 - m4rch3n1ng:144792-cow-diag, r=davidtwco
Add suggestion to `.to_owned()` used on `Cow` when borrowing

fixes rust-lang/rust#144792
supersedes rust-lang/rust#144925 with the review comments addressed

the tests suggested from @Kivooeo from https://github.com/rust-lang/rust/pull/144925#discussion_r2252703007 didn't work entirely, because these tests failed due to error `[E0308]` mismatched types, which actually already provides a suggestion, that actually makes the code compile:

```
$ cargo check
error[E0308]: mismatched types
 --> src/main.rs:3:5
  |
1 | fn test_cow_suggestion() -> String {
  |                             ------ expected `std::string::String` because of return type
2 |     let os_string = std::ffi::OsString::from("test");
3 |     os_string.to_string_lossy().to_owned()
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `String`, found `Cow<'_, str>`
  |
  = note: expected struct `std::string::String`
               found enum `std::borrow::Cow<'_, str>`
help: try using a conversion method
  |
3 |     os_string.to_string_lossy().to_owned().to_string()
  |                                           ++++++++++++
```

now this suggestion is of course not good or efficient code, but via clippy with `-Wclippy::nursery` lint group you can actually get to the correct code, so i don't think this is too much of an issue:

<details>
<summary>the clippy suggestions</summary>

```
$ cargo clippy -- -Wclippy::nursery
warning: this `to_owned` call clones the `Cow<'_, str>` itself and does not cause its contents to become owned
 --> src/main.rs:3:5
  |
3 |     os_string.to_string_lossy().to_owned().to_string()
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/beta/index.html#suspicious_to_owned
  = note: `#[warn(clippy::suspicious_to_owned)]` on by default
help: depending on intent, either make the `Cow` an `Owned` variant
  |
3 |     os_string.to_string_lossy().into_owned().to_string()
  |                                 ++
help: or clone the `Cow` itself
  |
3 -     os_string.to_string_lossy().to_owned().to_string()
3 +     os_string.to_string_lossy().clone().to_string()
  |
$ # apply first suggestion
$ cargo c -- -Wclippy::nursery
warning: redundant clone
 --> src/main.rs:3:45
  |
3 |     os_string.to_string_lossy().into_owned().to_string()
  |                                             ^^^^^^^^^^^^ help: remove this
  |
note: this value is dropped without further use
 --> src/main.rs:3:5
  |
3 |     os_string.to_string_lossy().into_owned().to_string()
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  = help: for further information visit https://rust-lang.github.io/rust-clippy/beta/index.html#redundant_clone
  = note: `-W clippy::redundant-clone` implied by `-W clippy::nursery`
  = help: to override `-W clippy::nursery` add `#[allow(clippy::redundant_clone)]`
```

</details>

the actual error that we are looking for is error `[E0515]`, cannot return value referencing local variable, which was only present in the original issue due to automatic type inference assuming you want to return a cloned `Cow<'_, str>`, which is of course not possible. this is why i took the original test functions and turned them into closures, where it's less obvious that it's trying to return the wrong type.

r? davidtwco

(because you reviewed the last attempt)
(also, let me know if i should squash this down to one commit and add myself as the co-contributor)
2026-04-10 18:38:14 +02:00
Laurențiu Nicola
2629a77d33 Use last good clippy lints JSON in codegen 2026-04-10 19:36:39 +03:00
workflows-rust-analyzer[bot]
cdcd9b4274 internal: update generated lints 2026-04-10 19:36:18 +03:00
Laurențiu Nicola
9c7ad1aab4 Merge pull request #22013 from lnicola/bump-create-github-app-token
minor: Bump create-github-app-token
2026-04-10 16:20:28 +00:00
Laurențiu Nicola
247651d4f9 Bump create-github-app-token 2026-04-10 18:29:55 +03:00
Chayim Refael Friedman
a816b21f9e Merge pull request #22002 from Shourya742/2026-04-09-remove-try-normalize-use-tree
Remove try-normalize-use-tree
2026-04-10 15:17:40 +00:00
Laurențiu Nicola
32c1e174e2 Merge pull request #22011 from lnicola/gen-lints-token
internal: Use create-github-app-token to get token for gen-lints
2026-04-10 15:10:33 +00:00
Laurențiu Nicola
65bae63b98 Use create-github-app-token to get token for gen-lints 2026-04-10 17:59:57 +03:00
A4-Tacks
f1f6d566a3 fix: no imports on type anchor qualified path
Example
---
```rust
fn main() {
    <Bar as Foo>::foo$0
}
mod m {
    pub fn foo() {}
}
struct Bar;
trait Foo {}
impl Foo for Bar {}
```

**Before this PR**

```
fn foo() (use m::foo) fn()
```

**After this PR**

no any imports
2026-04-10 22:57:25 +08:00
Mark Rousskov
ea636aded5 Bump to 1.97.0 release 2026-04-10 10:49:37 -04:00
Gary Guo
4c61b30d75 bootstrap: auto-patch libgccjit.so for NixOS
Currently all downloaded rustc and LLVM components are auto patched on
NixOS, but this is not done for libgccjit.so, so when GCC backend is
enabled on NixOS, the build ICEs with errors like this:

    thread 'rustc' (2286205) panicked at compiler/rustc_codegen_gcc/src/lib.rs:191:9:
    Cannot load libgccjit.so: libzstd.so.1: cannot open shared object file: No such file or directory

Fix this by auto-patch libgccjit.so, too. `zstd` is added to the dependency
environment.

Signed-off-by: Gary Guo <gary@garyguo.net>
2026-04-10 15:46:54 +01:00
A4-Tacks
dacfa3c237 fix: no complete term expressions on qualified path
config: `rust-analyzer.completion.termSearch.enable: true`

Example
---
```rust
fn bar() -> Bar {
    <Bar>::$0
}

trait Foo { fn foo() -> Self; }
struct Bar;
impl Bar { fn bar() {} }
impl Foo for Bar {
    fn foo() -> Self { Bar }
}
```

**Before this PR**

```rust
fn bar()                  fn()
fn foo() (as Foo) fn() -> Self
ex Bar
ex Bar::foo()
ex bar()
```

**After this PR**

```rust
fn bar()                  fn()
fn foo() (as Foo) fn() -> Self
```
2026-04-10 22:09:47 +08:00
CoCo-Japan-pan
46befd885d Display only crate name for external trait impl restrictions 2026-04-10 22:40:29 +09:00
Jana Dönszelmann
b305aeef7a fixup rustdoc,clippy,rustfmt 2026-04-10 15:10:04 +02:00
erfanio
df98ac25ba Fix rustfmt relative custom command
When `rustfmt.overrideCommand` is a relative path, it's joined with the
workspace root to make it an absolute path. Without this the command
path can't be resolved, especially because rustfmt changes the cwd to
make sure rustfmt.toml works correctly.

Currently `run_rustfmt` only does this when it finds a `target_spec`
using `target_spec_for_file` which only works for the root file of the
target.

This commit changes it to use `TargetSpec::from_file` which works for
any file in the crate.
2026-04-10 22:36:48 +10:00
Trevor Gross
3af9faa6cd test: Move tidy_lists from update-api-list.py to a new crate
This is the first step of migrating `update-api-list.py` to something
that handles the compiler-builtins functions.
2026-04-10 06:30:25 -04:00
Scott McMurray
63d7f8e7ae Initial methods to start on transmute v2 2026-04-10 01:58:56 -07:00
Redddy
dbe3144517 Merge pull request rust-lang/rustc-dev-guide#2829 from reddevilmidzy/hir
Fix link to hir::Crate in lowering.md
2026-04-10 16:59:23 +09:00
Redddy
2455931791 Fix link to hir::Crate in lowering.md 2026-04-10 16:57:27 +09:00
Waffle Lapkin
fa73f032b8 don't try to remove drop_in_place calls in RemoveUnneededDrops 2026-04-10 09:32:35 +02:00
Redddy
7c23ee6fca Move reserved tests to keyword 2026-04-10 06:01:35 +00:00
Redddy
e110275cce Clean up unknown-lints ui tests 2026-04-10 06:01:35 +00:00
Redddy
d2e978ea74 Move unknown_lints tests into lint/unknown-lints dir 2026-04-10 06:01:26 +00:00
Redddy
df2fe313d4 Fix format and bless test 2026-04-10 05:40:28 +00:00
Redddy
70af5cf2a3 Move deref-patterns tests to pattern sub directory 2026-04-10 05:40:28 +00:00
Lewis McClelland
df9fb65d62 Fix grammar issues in armv7a-vex-v5 docs 2026-04-09 23:05:53 -04:00
Lewis McClelland
ae6376ad8f Instruct users to build std (not core) on armv7a-vex-v5 2026-04-09 23:03:33 -04:00
Lewis McClelland
c25fbebe15 Add C compilation instructions 2026-04-09 23:03:33 -04:00
Lewis McClelland
dd79b039e4 Add docs about SDKs on armv7a-vex-v5 2026-04-09 23:03:33 -04:00
Trevor Gross
5c66a58083 hex: Always print a leading + sign and the NaN payload
This is for debugging so always give us all useful output.
2026-04-09 21:02:32 -04:00
Trevor Gross
c2c30c9037 hex: Eliminate parser hacks needed for the previous MSRV 2026-04-09 21:02:32 -04:00
Brian Cain
a4fe265df0 hexagon: Implement __clear_cache using inline assembly
Implement `__clear_cache` for Hexagon targets in Rust. Hexagon has
separate instruction and data caches, so this flushes dirty data cache
lines with `dccleaninva`, invalidates stale instruction cache lines
with `icinva`, then issues an `isync` barrier.

Based on the compiler-rt implementation from
llvm/llvm-project#188411.
2026-04-09 20:10:55 -04:00
Trevor Gross
a6de51188b libm: Add tests against rug for i256 2026-04-09 20:05:51 -04:00
Trevor Gross
06ea8566a1 libm: Add basic tests for u256::shl
Duplicate the shr test style to have a simple check for edge cases.
2026-04-09 20:05:51 -04:00
lapla
2754a83cc6 Fix ICE in span_extend_prev_while with multibyte characters 2026-04-10 06:34:12 +09:00
WhySoBad
085e4f258c fix: fix doc comment 2026-04-09 22:01:25 +02:00
WhySoBad
4e7ec9144f fix: implement feedback 2026-04-09 21:30:56 +02:00
Ralf Jung
6428be17cb Merge pull request #4953 from RalfJung/hack-no-more
genmc tests: remove a hack that is no longer needed
2026-04-09 18:24:02 +00:00
Ralf Jung
a75e80c1fd remove unused type 2026-04-09 19:55:42 +02:00
Ralf Jung
c3c931a1fc genmc tests: remove a hack that is no longer needed 2026-04-09 19:55:34 +02:00
Sasha Pourcelot
ec3f4382df Fix error message in #[patchable_function_entry] 2026-04-09 17:09:23 +00:00
Sasha Pourcelot
6f87e0be69 use AcceptContext::single_element_list where possible 2026-04-09 17:09:23 +00:00
Sebastian Urban
1209a86841 Update libc to v0.2.184 2026-04-09 18:55:40 +02:00
Jonathan Brouwer
1ddb9f2d13 Revert #152369 because of multiple regressions
The regressions are documented in the PR comments.
This reverts commit 2972b5e, reversing changes made to f908263.
2026-04-09 18:53:59 +02:00
Sasha Pourcelot
cdcecc85ac fix error message for #[custom_mir] 2026-04-09 16:39:58 +00:00
Sasha Pourcelot
362e0f9160 special case expected_single_argument when no argument is provided 2026-04-09 16:39:58 +00:00
Lars Schumann
804f4953d2 constify Index(Mut), Deref(Mut) for Vec 2026-04-09 16:31:12 +00:00
mu001999
faa7966a5b fix #[expect(dead_code)] liveness propagation 2026-04-09 23:53:42 +08:00
linshuy2
878feaa4dd fix: unused_async FP for stubs with args 2026-04-09 15:36:06 +00:00
Jason Newcomb
46a80c238f fn_to_numeric_cast_any: Do not warn cast to raw pointer (#14109)
Fixes #12638

changelog: [`fn_to_numeric_cast_any`]: Fix false positive on a cast to
raw pointer
2026-04-09 15:20:47 +00:00
bit-aloo
b009e5f8b9 remove try-normalize-use-tree 2026-04-09 20:48:25 +05:30
Ralf Jung
54742188ad Merge pull request #4952 from RalfJung/rustup
Rustup
2026-04-09 14:18:17 +00:00
Ralf Jung
4e6323b756 re-enable new cargo build dir layout testing 2026-04-09 15:54:20 +02:00
Ralf Jung
67fd8460ed Merge ref '4c4205163abc' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: 4c4205163a
Filtered ref: d09bed217e03a25403a0294a935c52309ae5d084
Upstream diff: 30d0309fa8...4c4205163a

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-09 15:53:57 +02:00
Ralf Jung
630cdae69d Prepare for merging from rust-lang/rust
This updates the rust-version file to 4c4205163a.
2026-04-09 15:53:46 +02:00
Waffle Lapkin
32cc8b13c9 use MaybeDangling in std 2026-04-09 15:51:46 +02:00
bjorn3
9e4bb84904 Reduce visibility of OngoingCodegen fields 2026-04-09 10:58:59 +00:00
bjorn3
25a84cfd6d Store a PathBuf rather than SerializedModule for cached modules
In cg_gcc ModuleBuffer already only contains a path anyway. And for
moving LTO into -Zlink-only we will need to serialize MaybeLtoModules.
By storing a path cached modules we avoid writing them to the disk a
second time during serialization of MaybeLtoModules.
2026-04-09 10:57:18 +00:00
Ralf Jung
a33321cc19 Merge pull request #4951 from KMiri-rs/stack-borrow-bitfields
fix the bitfield meanings of stacked_borrow item
2026-04-09 06:23:15 +00:00
The rustc-josh-sync Cronjob Bot
6ea1978117 Merge ref 'd0442e2800d3' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@d0442e2800
Filtered ref: rust-lang/compiler-builtins@9ead3e918f
Upstream diff: 0e95a0f4c6...d0442e2800

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-09 04:58:31 +00:00
The rustc-josh-sync Cronjob Bot
5fd302043b Prepare for merging from rust-lang/rust
This updates the rust-version file to d0442e2800.
2026-04-09 04:56:10 +00:00
zjp
5c57c5a65c fix the bitfield meanings of stacked_borrow item 2026-04-09 03:43:49 +00:00
Jacob Pratt
624a067ea8 Rollup merge of #155007 - josetorrs:rename-is-impl-trait, r=WaffleLapkin,Kivooeo
renaming method is_impl_trait to is_opaque

Completing one of the tasks mentioned in this issue: https://github.com/rust-lang/rust/issues/154941

r? @WaffleLapkin
2026-04-08 23:04:00 -04:00
WhySoBad
beaf7ee35a feat: also check that received buffers match 2026-04-08 23:27:39 +02:00
Brian Cain
d11e39623b Hexagon: add scalar arch-version target features (v60-v79, audio)
Add target features corresponding to Hexagon LLVM CPU generations to
complement the existing HVX vector features. These are needed for
gating scalar intrinsics by architecture version.

New features: audio, v60, v62, v65, v66, v67, v68, v69, v71, v73, v75, v79

Each version implies the previous (e.g. v68 implies v67 which implies
v66, etc.), matching LLVM's ArchV60-ArchV79 subtarget features.

Also adds hexagon revisions to the feature-hierarchy test to verify
the implied feature chains work correctly.
2026-04-08 14:22:30 -07:00
WhySoBad
3c4dfb4bbb docs: add comment when registering new source 2026-04-08 23:10:43 +02:00
WhySoBad
df1b8b8c18 fix: fix panic when multiple threads block on same fd 2026-04-08 23:08:03 +02:00
Ralf Jung
8dcf94ec6f reword 2026-04-08 23:00:00 +02:00
Jose
84f3530926 fixing clippy reference 2026-04-08 16:58:59 -04:00
Ralf Jung
f3ed56d6b1 unsafe keyword docs: bring back unsafe_op_in_unsafe_fn lint discussion 2026-04-08 22:51:35 +02:00
Folkert de Vries
aedb8dfff4 Merge pull request #2074 from androm3da/hexagon-hvx-case-preserved
hexagon: Preserve original Q6 naming case for HVX intrinsics
2026-04-08 20:50:09 +00:00
bors
810f8e4a40 Auto merge of #153838 - oli-obk:use-tree-span, r=davidtwco
Use fine grained component-wise span tracking in use trees

This often produces nicer spans and even doesn't need a Span field anymore (not that I expect the unused field to affect any perf, but still neat).
2026-04-08 20:09:27 +00:00
malezjaa
cf6aa22df5 update thin-vec 2026-04-08 21:09:07 +02:00
malezjaa
39f7cdb8e6 update thin-vec 2026-04-08 21:09:07 +02:00
Brian Cain
f8879e326f hexagon: Preserve original Q6 naming case for HVX intrinsics 2026-04-08 09:54:47 -07:00
dianne
35be9f2208 don't leak internal temporaries from dbg! 2026-04-08 08:52:47 -07:00
Ralf Jung
e44bb8df4c Merge pull request #4948 from RalfJung/genmc-always-configure
genmc-sys: remove always_configure hack
2026-04-08 14:56:56 +00:00
Ralf Jung
66580a38d9 genmc-sys: remove always_configure hack 2026-04-08 16:31:20 +02:00
Folkert de Vries
5a44da6067 make vld4q portable 2026-04-08 13:53:59 +02:00
Oli Scherer
78438c0135 Use fine grained component-wise span tracking in use trees 2026-04-08 12:37:25 +02:00
Paul Mabileau
962e9e2aab Test(lib/sync): Fix test_rwlock_max_readers for x86 Win7
The recently-added test currently systematically deadlocks when running
it under i686 Windows 7, but not x86_64 that passes it fine. This
therefore fixes the test for the target.

Empirically, the correct value for `MAX_READERS` seems to be `2^28 - 1`:
removing the `- 1` re-introduces the deadlock, at least under our
testing environment. This fix thus uses this value. However, I have no
real justification to support that, because I find myself a bit at a
loss when comparing the implementation details, the comment added above
the test and what the current value is; some help would therefore be
nice in this aspect. Also, the value change is restricted to 32-bit Win7
as there is no evidence to support it should be done for other targets.

Signed-off-by: Paul Mabileau <paul.mabileau@harfanglab.fr>
2026-04-08 10:50:37 +02:00
Ralf Jung
3fda203dce Merge pull request #4946 from rust-lang/rustup-2026-04-08
Automatic Rustup
2026-04-08 07:21:48 +00:00
Ralf Jung
f373acf337 disable new build dir layout again due to problems 2026-04-08 08:59:10 +02:00
The Miri Cronjob Bot
1a2291f7c9 Merge ref '30d0309fa821' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@30d0309fa8
Filtered ref: rust-lang/miri@a005b637c3
Upstream diff: bcded33165...30d0309fa8

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-08 05:37:40 +00:00
The Miri Cronjob Bot
bff890be84 Prepare for merging from rust-lang/rust
This updates the rust-version file to 30d0309fa8.
2026-04-08 05:30:05 +00:00
linshuy2
3351369d43 Enhance manual_filter to cover and_then 2026-04-07 22:58:06 +00:00
Nicholas Nethercote
cc74de3f9a Remove HashStable impl for [hir::Attribute].
This impl skips:
- All doc comments
- A handful of other attributes, mostly `rustc_*` ones related to
  incremental compilation testing.

This skipping originated in #36025 and was extended a couple of times,
e.g. in #36370. Those PRs don't have any explanation of why the skipping
exists. Perhaps the reasoning was that doc comments should only affect
rustdoc and rustdoc doesn't use incremental compilation? But doc
comments end up in metadata, and there is a query `attrs_for_def` that
returns a `&'tcx [hir::Attribute]`. So skipping some attributes just
seems plainly wrong.

This commit removes the impl, which means `[hir::Attribute]` hashing
falls back to the default impl for `[T]`. This has no noticeable effect
on the test suite. It does slightly hurt performance, because of the doc
comments. This perf regression seems worth it for the correctness
benefits.
2026-04-08 08:52:46 +10:00
Jason Newcomb
f5f3c2f30a Truncate constants to target type in comparison (#16782)
changelog: [`bad_bit_mask`]: truncate constant to target type before
warning about impossible equality

Fixes rust-lang/rust-clippy#16781
2026-04-07 19:34:09 +00:00
Amanieu d'Antras
3d93de5f0e Merge pull request #2068 from heiher/loong-clippy
loongarch: Remove unnecessary `transmute` calls
2026-04-07 13:16:58 +00:00
Trevor Gross
cea20e0e61 ci: Increase the timeout for benchmark jobs to 30 minutes
The i686 job has sometimes hit the existing 20 minute limit when things
take an extra long time to download.
2026-04-07 08:44:34 -04:00
Trevor Gross
2df972607e build: Fix c-b builds always being marked dirty 2026-04-07 08:44:34 -04:00
Trevor Gross
f5ca8e59fb build: Use a single configure file for all libraries
Some libraries already share a lot, but there is still some repeated or
scattered config. Centralize this all in `libm/configure.rs`.
2026-04-07 08:29:12 -04:00
Trevor Gross
2b288d32b5 build: Make c-b configue::Target match libm configure::Config
Rename the fields and the type use to make it easier to combine these
two structs.
2026-04-07 08:29:12 -04:00
Daria Sukhonina
aa6150b680 Refactor arena_cache query values 2026-04-07 13:59:34 +03:00
Trevor Gross
25104546ce test: Extract flat_maps to product* functions 2026-04-07 05:58:18 -04:00
Trevor Gross
bbcba28cfc test: Use a more consistent setup for iter and steps 2026-04-07 05:58:18 -04:00
Alice Ryhl
46a84f6c4f Add run-pass test for dyn Receiver 2026-04-07 08:55:27 +00:00
Alice Ryhl
2d8ae32c58 Add a test for the ICE 2026-04-07 08:51:47 +00:00
Alice Ryhl
4e75261442 Add Sized supertrait for CoerceUnsized and DispatchFromDyn 2026-04-07 08:42:09 +00:00
Trevor Gross
5678e6187d test: Use let chains to simplify patterns in generator macros 2026-04-07 04:15:24 -04:00
Trevor Gross
5344da9654 test: Make use of strict_mul rather than checked_mul(..).unwrap() 2026-04-07 04:15:24 -04:00
Trevor Gross
73cb91db4e test: Give helper functions in spaced more accurate names 2026-04-07 04:15:24 -04:00
Waffle Lapkin
6a4eefde2d ty::Alias refactor: fix clippy 2026-04-07 10:08:12 +02:00
Samuel Tardieu
c4e5a77b76 unneeded_wildcard_pattern.rs: fix typo (rathter -> rather) (#16818)
changelog: none
2026-04-07 07:33:22 +00:00
David Gauch
c7c9117326 Add const Default impls for LazyCell and LazyLock 2026-04-06 23:53:29 -07:00
Ralf Jung
0fbaf47e5e Merge pull request #4945 from rust-lang/rustup-2026-04-07
Automatic Rustup
2026-04-07 06:10:23 +00:00
The Miri Cronjob Bot
51dec7515b fmt 2026-04-07 05:38:33 +00:00
The Miri Cronjob Bot
315c167967 Merge ref 'bcded331651b' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@bcded33165
Filtered ref: rust-lang/miri@d2d41cf6da
Upstream diff: c92036b45b...bcded33165

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-07 05:37:59 +00:00
The Miri Cronjob Bot
7a501c5240 Prepare for merging from rust-lang/rust
This updates the rust-version file to bcded33165.
2026-04-07 05:29:27 +00:00
Zachary S
7d35719021 Add doctest for Box/Rc/Arc::into_array 2026-04-06 23:54:50 -05:00
Zachary S
938c5b5df6 Make Box/Rc/Arc::into_array allocator-aware 2026-04-06 23:41:37 -05:00
WANG Rui
548d790dd8 loongarch: Remove unnecessary transmute calls
This commit removes unnecessary `transmute` calls to resolve clippy
warnings.
2026-04-07 11:41:06 +08:00
Trevor Gross
6bbf64e1dd roundeven: Use an assembly implementation on i586
Add an assembly implementation for roundeven which also works for
`rint`, similar to the existing `ceil` and `floor` implementations. This
resolves cases where values close to the *.5 boundary would round the
incorrect direction, such as -519629176421.49976 (tested in
`case_list`).
2026-04-06 20:57:45 -04:00
Daniel Scherzer
c40e988d19 unneeded_wildcard_pattern.rs: fix typo (rathter -> rather) 2026-04-06 16:45:50 -07:00
Ariel Ben-Yehuda
1b96797c08 address review comments 2026-04-07 02:12:57 +03:00
Sayantan Chakraborty
0a4221d1c0 Merge pull request #2066 from folkertdev/basic-miri-roundtrip
Basic miri store/load roundtrip
2026-04-06 22:57:43 +00:00
Ariel Ben-Yehuda
a0ff19d8ec reset mitigation status on a mitigation option as per the RFC 2026-04-07 00:52:42 +03:00
Ariel Ben-Yehuda
b4bfd7fa43 address review comments 2026-04-07 00:52:42 +03:00
Ariel Ben-Yehuda
c55bfc66a6 enforcable -> enforceable 2026-04-07 00:52:42 +03:00
Ariel Ben-Yehuda
cc2d560ebf use -Z deny-partial-mitigations instead of -Z allow-partial-mitigations=! 2026-04-07 00:52:41 +03:00
Ariel Ben-Yehuda
3600f4cd2c EnforcableMitigation => DeniedPartialMitigation 2026-04-07 00:52:41 +03:00
Ariel Ben-Yehuda
eb89ca9b77 enforced => enforcable mitigation 2026-04-07 00:52:41 +03:00
Ariel Ben-Yehuda
51b2b93239 allow denying mitigations in earlier editions 2026-04-07 00:52:41 +03:00
Ariel Ben-Yehuda
daedc77e84 address review comments 2026-04-07 00:52:41 +03:00
Ariel Ben-Yehuda
de2408aeed Implement -Z allow-partial-mitigations (RFC 3855)
This implements `-Z allow-partial-mitigations` as an unstable option,
currently with support for control-flow-guard and stack-protector.

As a difference from the RFC, we have `-Z allow-partial-mitigations=!foo`
rather than `-Z deny-partial-mitigations=foo`, since I couldn't find an easy
way to have an allow/deny pair of flags where the latter flag wins.

To allow for stabilization, this is only enabled starting from the next edition. Maybe a
better policy is possible (bikeshed).
2026-04-07 00:52:41 +03:00
Folkert de Vries
8e2069e76c run some aarch64 tests with miri on CI 2026-04-06 19:39:21 +02:00
Folkert de Vries
4b52401221 run test_vld3q tests with miri on CI 2026-04-06 19:39:20 +02:00
Folkert de Vries
cb0d495dae support roundtrip of vst3q 2026-04-06 19:39:20 +02:00
Folkert de Vries
8f3850c74c check that store/load rountrip initializes all bytes 2026-04-06 19:39:20 +02:00
Folkert de Vries
ebfdd898ca Merge pull request #2067 from rust-lang/rustc-pull
Rustc pull update
2026-04-06 17:22:54 +00:00
Folkert de Vries
598640b101 disable hexagon tests for now 2026-04-06 19:13:42 +02:00
Martin Nordholts
2d14e741ca borrowck: Apply user_arg_index nomenclature more broadly
No change in behavior. Only renames and a couple of added comments.
2026-04-06 17:34:21 +02:00
Ada Alakbarova
49a2f386f9 Unneeded wildcard improvement (#16733)
*[View all
comments](https://triagebot.infra.rust-lang.org/gh-comments/rust-lang/rust-clippy/pull/16733)*

changelog: [`unneeded_wildcard_pattern`]: add support for struct
constructs.

Closes [#16638](https://github.com/rust-lang/rust-clippy/issues/16638)

The existing lint only looks at tuples and tuplestructs. This change
adds support for standard structs, looking for cases
where one or more `_` immediately preceed a `..`. The preceeding `_`
members may be omitted, as they will be collected by the `..` operator.
2026-04-06 15:04:13 +00:00
zedddie
baf246f27e gate tuple const params behind adt_const_params 2026-04-06 14:26:21 +02:00
Ralf Jung
7f3523947b Merge pull request #4942 from RalfJung/float-err-bounds
float test: double error tolerance with imprecise ops on both sides
2026-04-06 08:49:02 +00:00
Ralf Jung
0b6423de62 float test: double error tolerance with imprecise ops on both sides 2026-04-06 10:25:56 +02:00
cijiugechu
1ee6e9a1ff Fix ICE for inherited const conditions on const closures 2026-04-06 15:59:58 +08:00
Rain
bbb9e3bb4a libtest: use binary search for --exact test filtering
The test array is sorted by name at compile time. When `--exact` is
passed in, use binary search for O(f log n) lookups instead of an O(n)
linear scan, under the assumption that f << n (which is true for the
most relevant cases).

This is important for Miri, where the interpreted execution makes the
linear scan very expensive.

I measured this against a repo with 1000 empty tests, running
`cargo +stage1 miri nextest run test_00` (100 tests) under hyperfine:

* Before (linear scan): 49.7s ± 0.6s
* After (binary search): 41.9s ± 0.2s  (-15.7%)

I also tried a few other variations (particularly swapping matching tests to the front of the list + truncating the list), but the index + swap_remove approach proved to be the fastest.

Questions:

- [ ] To be conservative, I've assumed that test_main can potentially receive an unsorted list of tests. Is this assumption correct?
2026-04-05 21:11:49 -07:00
erfanio
8d96fa0557 Merge rust-analyzer settings instead of overwriting 2026-04-06 12:38:23 +10:00
erfanio
d4773683a6 Use double quotes consistently 2026-04-06 12:11:50 +10:00
erfanio
002634043f Use skip_comments to strip comments 2026-04-06 11:55:39 +10:00
erfanio
314c14a9a6 Address code review comments 2026-04-06 11:45:05 +10:00
jim
df2f81b8e7 add struct support to unneeded_wildcard_pattern lint
Apply suggestions from code review

Co-authored-by: Ada Alakbarova <58857108+ada4a@users.noreply.github.com>
2026-04-05 14:26:56 -04:00
CoCo-Japan-pan
72c1d65037 Inline krate 2026-04-05 20:54:36 +09:00
Samuel Tardieu
389a32a4c3 perf: disable nonminimal_bool by default (#16761)
After performance concers on the `nonminimal_bool` lint, we [performed a
crater run](https://github.com/rust-lang/rust/issues/153883)

This crater run revealed that in 19120 suggestions taken from 1.3
million crates, only about 36% had resulted in multi-terminal
suggestions (suggestions that were not only a single boolean).

This suggests that most cases of this lint firing, the expression that
triggered was pretty simple. And thus, we should not take such a huge
toll for a lint that isn't that useful.

In the future, a rewrite of that `bool_expr` function could be very
useful to alleviate the performance toll. Because clearly running the
Quine McCluskey algorithm on all those boolean operations is not ideal.

---

## Performance report:

`cargo clippy` -> 5,077,447,157 icount
`cargo check` -> 3,629,576,891 icount

So the Clippy that `rustup` delivers is about 1.4b instructions more
than `cargo check`.

`NonminimalBool` lint pass -> 318,169,034

$$\frac{nonminimal\\_bool}{clippy-check}*100 = 21.97496844$$

So, the `NonminimalBool` lint pass is about 22% of all Clippy-exclusive
instruction count.

---

After this change, we can now compare the Clippy BUILT FROM MASTER, NOT
DELIVERED BY RUSTUP, with the Clippy from this PR.

`master/target/release/cargo-clippy` -> 5,296,838,955 (Slower than
Rustup)
`pr/target/release/cargo-clippy` -> 4,977,035,941.

So, $master - PR = 319803014$, which is the exact icount of
`Nonminimal_bool` and about 22% of Clippy's whole execution time.

Profiled on `syn-2.0.71`, with Callgrind.

changelog:[`nonminimal_bool`]: Move to `pedantic`.
changelog:[`overly_complex_bool_expr`]: Move to `pedantic`.
2026-04-05 11:54:26 +00:00
Walnut
472b966548 allow windows-gnu targets to embed gdb visualizer scripts 2026-04-05 02:19:59 -05:00
Ralf Jung
97010af47d Merge pull request #4941 from rust-lang/rustup-2026-04-05
Automatic Rustup
2026-04-05 06:48:35 +00:00
Ralf Jung
82b637b450 float test: increase ULP tolerance 2026-04-05 08:23:44 +02:00
llogiq
ab9cb427b8 Rework expr_use_ctxt into an iterator over successive use sites. (#16784)
This is going to be used as part of more thoroughly checking whether we
can change the type of an expression. e.g. `range_plus_one` suggests
changing `Range` to `RangeInclusive`.

changelog: none
2026-04-05 06:02:51 +00:00
The Miri Cronjob Bot
1d807ed41d Merge ref 'c92036b45bab' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@c92036b45b
Filtered ref: rust-lang/miri@a4b2f0cfed
Upstream diff: 55e86c9968...c92036b45b

This merge was created using https://github.com/rust-lang/josh-sync.
2026-04-05 05:37:25 +00:00
The Miri Cronjob Bot
446629dcb4 Prepare for merging from rust-lang/rust
This updates the rust-version file to c92036b45b.
2026-04-05 05:29:21 +00:00
CoCo-Japan-pan
6f9727342f Add non-ancestor errors involving restrictions to other crates 2026-04-05 13:18:00 +09:00
CoCo-Japan-pan
2f400deab3 Modify restriction_path 2026-04-05 13:15:21 +09:00
llogiq
1e0b66ef7e fix: unnecessary type cast causing a compile error (#16796)
In some cases, removing a cast that looks unnecessary can
still change type inference, even when the cast is to the
expected same type.

The lint now handles casts that flow through
intermediate expressions (e.g. calls, blocks, let
bindings, loops...). It also treats placeholder
generics (e.g. `::<_>`) as inference sensitive.

Added regression tests with similar behavior
as the original bug, some edge cases and
tests to check if false negative cases
weren't created.

Closes rust-lang/rust-clippy#16449

changelog: [`unnecessary_cast`]: fixed a suggestion to remove a cast
that can cause a compilation error if followed.
2026-04-04 20:12:58 +00:00
llogiq
3cd5a6569a [unsafe_removed_from_name]: skip linting when renaming to '_' (#16802)
closes: rust-lang/rust-clippy#16768

I agree with the:
> importing it just to get the side effects of the trait being in scope
(anonymously, via as _) is not renaming it...

even without changing the name, we still not able to see it's original
name when calling a trait method, so I think this should be fine.

---

changelog: [`unsafe_removed_from_name`]: skip linting when renaming to
'_'
2026-04-04 19:32:30 +00:00
dswij
ee4aff91c5 Multiple fixes to FNs of question_mark (#16769)
Closes rust-lang/rust-clippy#16751

changelog: [`question_mark`] fix FN for manual unwrap with `if let` or
`match`
changelog: [`question_mark`] fix FN when the match scrutinee is behind
reference
changelog: [`question_mark`] fix FN when match binding is behind `ref`
or `mut`
2026-04-04 15:56:33 +00:00
llogiq
80d86e3465 Update cargo_metadata to 0.23 (#16803)
Updates cargo_metadata to 0.23 and fixes all the resultant issues.

changelog: none
2026-04-04 13:23:04 +00:00
CoCo-Japan-pan
65effbf5d6 Add a FIXME for rustdoc handling impl restrictions 2026-04-04 21:42:52 +09:00
Philipp Krones
dc57fd7f53 Merge commit '88f787d193fb1f0491b001288e82b5574c080606' into clippy-subtree-update 2026-04-04 14:39:31 +02:00
Brian Cain
312b9946c7 c-b: Add hexagon common entry/exit ABI routines and memcpy_dwloop
Add callee-saved register save/restore routines for three hexagon ABIs
(abi1, abi2, legacy) and a double-word loop memcpy implementation. Also
add a FALLTHROUGH_TAIL_CALL macro to func_macro.s for chaining function
entry points without branches.

Refer to c1fd7d7a1f/compiler-rt/lib/builtins/hexagon for corresponding clang-rt hexagon builtin source.
2026-04-04 04:45:51 -04:00
Andre Bogus
a4e5f908af slightly optimize the non-camel-case-types lint 2026-04-04 10:32:59 +02:00
CoCo-Japan-pan
4f1260910a Remove the type alias for Path<'hir, DefId> 2026-04-04 17:16:14 +09:00
CoCo-Japan-pan
5863660b0d Remove shorthand from HIR 2026-04-04 16:53:30 +09:00
CoCo-Japan-pan
159f1f24fa Call visit_path_segment directly 2026-04-04 16:41:57 +09:00
Jonathan Brouwer
d88d64be5e Fix attribute order implementation 2026-04-03 23:41:40 +02:00
Jacob Adam
26799d9112 Update cargo_metadata to 0.23. 2026-04-03 20:11:43 +01:00
J-ZhengLi
d5f106507b [unsafe_removed_from_name]: skip lint when renaming to '_' 2026-04-04 02:07:40 +08:00
Arthur Carcano
5ac90c6def Clarify ascii whitespace exclusion of vertical tab in the doc
This especially means that for c: char, c.is_ascii() &&
c.is_whitespace() does **not** imply c.is_ascii_whitespace().
2026-04-03 19:04:03 +02:00
apiraino
69345f6feb Fix GPU target notification group links 2026-04-03 11:22:17 +02:00
Edvin Bryntesson
39f52ee1e2 deduplicate unused expect lints 2026-04-03 11:08:11 +02:00
Edvin Bryntesson
d0594c1ad7 bless tests and tidy
also removes E0452 and splits
`tests/rustdoc-ui/lints/renamed-lint-still-applies` into 2 tests

this is because of delayed warn lint being lost on compiler aborting on
error
2026-04-03 11:08:11 +02:00
Edvin Bryntesson
f04b718655 integrate parsed lint attrs into clippy 2026-04-03 11:08:10 +02:00
Guilherme Silva
b269a2b71f fix: unnecessary type cast causing a compile error
In some cases, removing a cast that looks unnecessary
can still change type inference, even when the cast is
to the expected same type.

The lint now handles casts that flow through
intermediate expressions (e.g. calls, blocks, let
bindings, loops...). It also treats placeholder
generics (e.g. `::<_>`) as inference sensitive.

Added regression tests with similar behavior
as the original bug, some edge cases and
tests to check if false negative cases
weren't created.

Closes #16449
2026-04-02 22:47:35 +01:00
Jules Bertholet
e9b36bd374 core::unicode: Replace Cased table with Lt
Shaves off 368 bytes from the total size of all Unicode data tables.
2026-04-02 10:30:24 -04:00
Trevor Gross
719d7f9e17 bench: Rename the benchmark baselines
These no longer test just softfloat and hardfloat, but also the fallback
implementations in `mem` compared to those that make use of assembly.
Change the baseline names to be more accurate of the difference.
2026-04-02 04:05:53 -04:00
Trevor Gross
dee26f70d1 libm: Deprecate feature = "force-soft-float"
This was needed while some codegen backends did not support inline
assembly, or ran into circular issues using vector intrinsics. All such
issues have since been resolved with the in-tree backends. The remaining
need was to be able to toggle these features in tests, which we can do
via the enabled-by-default `arch` feature. Since there aren't any cases
requiring `force-soft-float`, remove its functionality and deprecate it.

It is possible that future codegen backends may have a similar need to
disable inline assembly until pairity with the LLVM backend can be
reached. In these cases rather than having `force-soft-float`, it would
be better to have rustc provide a `cfg(target_supports_inline_asm)`.
`build.rs` can then do something like:

    let nightly = cfg!(feature = "compiler-builtins") || cfg!(feature = "unstable");
    let asm_support = env::var("CARGO_CFG_TARGET_SUPPORTS_INLINE_ASM").is_ok();
    let arch_enabled = cfg!(feature = "arch") && (!nightly || (nightly && asm_support));
    set_cfg("arch_enabled", arch_enabled);

This is about what we have now with `cfg(target_has_reliable_f16)` and
`cfg(target_has_reliable_f128)` being set by rustc, which is
significantly easier to use than the `feature = "no-f16-f128"` that it
replaced. Having rustc directly tell us what it supports means we don't
need to bubble subtractive options up to bootstrap via a chain of Cargo
features that aren't really meant to support disabling things.

I'm sketching this out for future reference since it seems likely that
the need comes back up eventually.
2026-04-01 19:45:21 -04:00
Trevor Gross
5448797944 ci: Bump ubuntu:25.10 docker images to 26.04 2026-04-01 18:47:14 -04:00
Trevor Gross
2f57167feb Revert "ci: Don't re-archive the tar.xz benchmark baseline"
Unfortunately the `gh` CLI tool can't yet download non-zipped archives.
Attempting to do so says:

    error downloading baseline-icount-i686-202604011355-ba4c48868cad.tar.xz: error extracting zip archive: zip: not a valid zip file

Drop this change until the CLI is updated.

This reverts commit 0a57b9e3eda70c3673815fc47fad137a3c62da98.
2026-04-01 16:45:54 -04:00
okaneco
fd3a74dc9b core/num: Implement feature integer_cast_extras
Implement saturating, checked, and strict casting between
signed and unsigned integer primitives of the same bit-width.

Add `cast_integer` function to `overflow_panic.rs`
2026-04-01 15:42:44 -04:00
xizheyin
c4f14ad560 Avoid suggest format string field access for braced paths 2026-04-02 03:25:08 +08:00
Trevor Gross
6b97e039e4 c-b: Replace the no-asm feature with an opposite-polarity arch
Make `libm` and `compiler-builtins` use the same configuration:

* By default there is an `arch` feature which allows `core::arch` and
  inline assembly.
* Disabling the `arch` feature turns these off.

Positive feature flags are easier to reason about than negative, so this
will allow for some build script cleanup as well.
2026-04-01 09:49:04 -04:00
Trevor Gross
fc47fbcf51 ci: Don't re-archive the tar.xz benchmark baseline
The new version of `actions/upload-artifact` allows for skipping the
automatic file zipping, which is good because our files are already
compressed.
2026-04-01 09:04:29 -04:00
Mend Renovate
858156eb42 chore(deps): lock file maintenance 2026-04-01 06:15:30 -04:00
Mend Renovate
d89fb1df02 chore(deps): update github actions 2026-04-01 06:14:11 -04:00
Mend Renovate
9c41dadd30 chore(deps): update actions/upload-artifact action to v7 2026-04-01 06:10:47 -04:00
Mend Renovate
6dd2ec0ce5 chore(deps): update rust crate object to 0.39.0 2026-04-01 05:55:05 -04:00
Marco Ieni
7d709d16ad renovate: don't raise individual PRs for crates non breaking changes
Before this PR, we were receiving PRs when crate `1.2.3` was updated to
`1.3.0`. With this PR, we should receive PRs only when `2.0.0` is out.

Similar to https://github.com/rust-lang/crates-io-auth-action/pull/220
2026-04-01 05:31:28 -04:00
Jakub Beránek
1276db5745 Fix rustc-pull CI workflow 2026-04-01 11:23:04 +02:00
Jakub Beránek
c1c86519dc ci: Fix rustc-pull workflow
See https://github.com/rust-lang/josh-sync/pull/40.
2026-04-01 09:21:19 +00:00
Trevor Gross
b551fa8f03 c-b: Turn mem-unaligned from a feature to a cfg
For anything that doesn't need to be configurable via Cargo, using a
`cfg` rather than a feature is cleaner.
2026-04-01 04:51:47 -04:00
Trevor Gross
3975322675 build: Print build config if LIBM_BUILD_VERBOSE is set
Make it easier to see what is being enabled without enabling Cargo's
`-vv` output.
2026-04-01 04:51:47 -04:00
Trevor Gross
ed1274749d test: Turn feature = "no-sys-f128" and similar into plain cfg
These are internal configuration that Cargo doesn't need to be aware of.
Clean them up from the Cargo.toml feature list.
2026-04-01 02:55:13 -04:00
CoCo-Japan-pan
222292a951 Add UI tests for semantic checks of impl restrictions 2026-04-01 12:01:41 +09:00
CoCo-Japan-pan
cdbccf7275 Emit error in implementation of restricted trait 2026-04-01 12:01:41 +09:00
CoCo-Japan-pan
bda0fcea83 Lower impl restriction information to TraitDef 2026-04-01 12:01:41 +09:00
CoCo-Japan-pan
01793db93c Intravisit hir::ImplRestriction 2026-04-01 12:01:41 +09:00
CoCo-Japan-pan
232d064efd Lower impl restriction to HIR 2026-04-01 12:01:40 +09:00
CoCo-Japan-pan
d5c756acf3 Lower impl restriction to HIR 2026-04-01 12:01:40 +09:00
Trevor Gross
22579364d8 c-b: Clean up the mem feature
`mem` only enables the unmangled names; the functions are always
available via mangled names, so this doesn't have any purpose in our
tests. Thus, remove it from `builtins-test`.

The remaining `feature = "mem"` configuration in tests is for the
`aeabi_mem*` files, which call the compiler-builtins functions via
extern definitions. Move these to builtins-test-intrinsics, which is the
home of other tests that require unmangled symbols. Unfortunately these
tests have apparently not worked for a long time; this situation is
unchanged.
2026-03-31 21:54:45 -04:00
Trevor Gross
9a7c3e1607 bench: Enable unmangled-names when running benchmarks
Ensure that our compiler-builtins is providing the runtime, so we can
see the effect of changes in c-b on libm functions. This was happening
implicitly before because the `mangled-names` feature was not enabled in
tests, so unmangled names were exposed. In commit "c-b: Change the
`mangled-names` feature to `unmangled-names`" things were reversed,
meaning the unmangled names are no longer exposed by default, so our
benches started using the platform symbols. (Hence apparent regressions
in fmaf128, ldexpf128, powif128, and scalbnf128).
2026-03-31 21:35:45 -04:00
Trevor Gross
ce25428693 c-b: Change the mangled-names feature to unmangled-names
This feature is somewhat backwards because the mangled names are always
available; enabling the `mangled-names` feature disables unmangled
names. This was likely somehow related to default features when the
crate was published on crates.io.

Rename the feature and reverse the logic such that unmangled names are
exposed when the feature `unmangled-names` is enabled.

Note that this changes some benchmarking logic; see the following commit
message for details.
2026-03-31 21:35:45 -04:00
Trevor Gross
cb4025be48 c-b: Remove the mangled-names feature from builtins-test
This isn't used anywhere in CI and there doesn't seem to be a reason
that it would need to be toggled. Enable `mangled-names` on the
`compiler-builtins` dependency by default and remove the from
`builtins-test`.
2026-03-31 21:35:45 -04:00
Trevor Gross
cf6b8b38c0 ci: Allow both benchmark versions to run on regressions
Don't exit immediately if a benchmark has regressions. Instead, save the
error and continue with the rest, then exit at the end.
2026-03-31 19:46:58 -04:00
Trevor Gross
0f19a2db1a ci: Temporarily disable the RISC-V runners
There are a limited amount of runners for these jobs, which is causing a
slow point in CI. Once more runners are available we can re-enable the
job.
2026-03-31 19:29:48 -04:00
erfanio
6f815063a3 Update neovim instructions for neovim 0.11+ 2026-04-01 08:38:45 +11:00
Trevor Gross
03e408b22b ci: Explicitly set the compiler-builtins feature for symcheck
Since this is no longer a default feature, we need to enable it to avoid
getting errors about symbols from `core`.
2026-03-31 17:02:03 -04:00
The rustc-josh-sync Cronjob Bot
2bea478362 Merge ref '0e95a0f4c677' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@0e95a0f4c6
Filtered ref: rust-lang/compiler-builtins@84dcb0e1ae
Upstream diff: db3e99bbab...0e95a0f4c6

This merge was created using https://github.com/rust-lang/josh-sync.
2026-03-31 20:37:37 +00:00
The rustc-josh-sync Cronjob Bot
cf46b0a82c Prepare for merging from rust-lang/rust
This updates the rust-version file to 0e95a0f4c6.
2026-03-31 20:35:11 +00:00
Ubiratan Soares
3f2745ce6e ci: fix rustc-pull permissions 2026-03-31 16:24:25 -04:00
may
697ae4ac10 apply review suggestions and move Cow sym to rustc 2026-03-31 21:32:31 +02:00
The rustc-josh-sync Cronjob Bot
79e3df625d Merge ref 'e4fdb554ad2c' from rust-lang/rust
Pull recent changes from https://github.com/rust-lang/rust via Josh.

Upstream ref: rust-lang/rust@e4fdb554ad
Filtered ref: rust-lang/stdarch@ae05da8bd6
Upstream diff: eda4fc7733...e4fdb554ad

This merge was created using https://github.com/rust-lang/josh-sync.
2026-03-31 15:50:44 +00:00
The rustc-josh-sync Cronjob Bot
8e815f9ae1 Prepare for merging from rust-lang/rust
This updates the rust-version file to e4fdb554ad.
2026-03-31 15:48:28 +00:00
Trevor Gross
f9aeb48c51 libm: Add an approx module
As we port more correctly rounded implementatinos from CORE-MATH, it
would be nice to keep the existing versions around since they are
simpler, typically smaller and faster, and easier to port to other float
types. The implementations have also been reasonably well tested. 

Introduce an `approx` module that will serve as a home for these. As the
first member, add back the old `cbrt` implementation that was replaced
in 75a7f3df3ed7 ("Port the CORE-MATH version of `cbrt`").
2026-03-31 06:41:10 -04:00
Trevor Gross
816765baa0 hypot: Add cr_hypot from CORE-math
Replace our current implementation with one that is correctly rounded.

Source: 93d9f3bab7/src/binary64/hypot/hypot.c
2026-03-31 05:56:54 -04:00
Trevor Gross
2dc08eaf3d hypot: Move the existing implementation to the approx module 2026-03-31 05:56:54 -04:00
Nicholas Nethercote
deb901c896 Use closures more consistently in dep_graph.rs.
This file has several methods that take a `FnOnce() -> R` closure:
- `DepGraph::with_ignore`
- `DepGraph::with_query_deserialization`
- `DepGraph::with_anon_task`
- `DepGraphData::with_anon_task_inner`

It also has two methods that take a faux closure via an `A` argument and
a `fn(TyCtxt<'tcx>, A) -> R` argument:
- DepGraph::with_task
- DepGraphData::with_task

The rationale is that the faux closure exercises tight control over what
state they have access to. This seems silly when (a) they are passed a
`TyCtxt`, and (b) when similar nearby functions take real closures. And
they are more awkward to use, e.g. requiring multiple arguments to be
gathered into a tuple. This commit changes the faux closures to real
closures.
2026-03-31 20:21:05 +11:00
Tim (Theemathas) Chirananthavat
c775de4bee Make DerefPure dyn-incompatible
Fixes https://github.com/rust-lang/rust/issues/154619.

If `DerefPure` were dyn-compatible, a trait object of a subtrait of
`DerefPure` could be created by unsize-coercing an existing type that
implements `DerefPure`. But then the trait object could have its own
non-pure impl of `Deref`/`DerefMut`, which is unsound, since the trait
object would implement `DerefPure`. Thus, we make `DerefPure`
dyn-incompatible.
2026-03-31 11:29:40 +07:00
Crystal Durham
fb99fbec84 add missing core::process module docs 2026-03-30 19:05:26 -04:00
Crystal Durham
3a311edc97 add abort_immediate 2026-03-30 18:55:59 -04:00
Trevor Gross
3d384fae24 test: Also test the non-generic function for rounding ops 2026-03-30 18:19:22 -04:00
Marco Ieni
e273f945c8 ci: Rename updateTypes to matchUpdateTypes in renovate config
See https://github.com/rust-lang/team/pull/2359
2026-03-30 21:32:29 +00:00
Trevor Gross
7803d01f1b test: Benchmark i256 right shifts
Additionally, update the formatting of the macro invocations to use the
new syntax.
2026-03-30 17:09:20 -04:00
Trevor Gross
b10da67cfc libm: Use the shorthand cfg(x86_no_sse2) in more places 2026-03-30 15:21:45 -04:00
Trevor Gross
1560c85df4 config: Replace cfg(x86_no_sse) with cfg(x86_no_sse2)
We use this option for both `f32`- and `f64`-related configuration, but
the original SSE only had support for single-precision operations.
Update this config to check for the SSE2 feature instead, which includes
double-precision support.

In practice this config is mostly used to differentiate between the i586
target (no SSE required) and the i686 target (SSE2 required) so for that
purpose, the existing behavior is fine. Building on an i586 baseline
with SSE enabled (but not sse2) also isn't really something we worry
about, so this change is mostly only for improving code readability.
2026-03-30 15:21:45 -04:00
Jason Newcomb
8322ae2cfb Rework expr_use_ctxt into an iterator over successive use sites. 2026-03-30 11:54:43 -04:00
Alex Crichton
c14d998c2a Update to wasi-sdk-32 in CI/releases
Similar to prior updates such as 149037. This notably pulls in some bug
fixes for wasi-libc around nonblocking I/O and networking.
2026-03-30 08:19:36 -07:00
Trevor Gross
419cad6d7e ci: Also use nextest to run compiler-builtins tests
Currently nextest is always installed but only used for libm. Enable it
for compiler-builtins too to help speed up CI.
2026-03-30 08:53:29 -04:00
Trevor Gross
cc4523f526 test: Increase the ULP allowed against musl for tanhf
thread 'musl_random_tanhf' (76230) panicked at libm-test/tests/compare_built_musl.rs:26:50:
    called `Result::unwrap()` on an `Err` value: 
        input:    (0.24503659,)
        as hex:   (0x1.f5d5bep-3,)
        as bits:  (0x1.f5d5bep-3,)
        expected: 0.24024732             0x1.ec06cap-3 0x1.ec06cap-3
        actual:   0.24024737             0x1.ec06d0p-3 0x1.ec06d0p-3

    Caused by:
        ulp 3 > 2

    thread 'musl_quickspace_tanhf' (38650234) panicked at libm-test/tests/compare_built_musl.rs:26:50:
    called `Result::unwrap()` on an `Err` value:
        input:    (0.19125812,)
        as hex:   (0x1.87b256p-3,)
        as bits:  (0x1.87b256p-3,)
        expected: 0.18895967             0x1.82fd4ap-3 0x1.82fd4ap-3
        actual:   0.18895972             0x1.82fd50p-3 0x1.82fd50p-3

    Caused by:
        ulp 3 > 2
2026-03-30 08:31:32 -04:00
Trevor Gross
bfb6050ebd libm: Make unit test setup consistent across rounding functions 2026-03-30 07:43:51 -04:00
Trevor Gross
4247543c4f libm: Add status output support to rint_status
Rename `rint_round` to `rint_status` since its rounding argument is not
being used, and add support for returning the status.
2026-03-30 07:43:51 -04:00
Trevor Gross
a6aa04cacd c-b: Use the libm Float trait
Similar to `Int`, `Float` is very similar between `compiler-builtins`
and libm. Remove the c-b version  and instead use the libm trait for
both crates.
2026-03-30 07:21:12 -04:00
Samuel Tardieu
ab1279e967 Truncate constants to target type in comparison 2026-03-30 13:11:55 +02:00
Trevor Gross
c87cad8477 c-b: Use libm Int, MinInt, u256, and related items
The libm and c-b versions of these are (intentionally) near identical.
Switch c-b to use the libm versions rather than having its own
definitions, which allows cleaning up a significant amount of code.
2026-03-30 05:33:51 -04:00
Trevor Gross
9673c6cd4e libm: Clean up an unused type parameter
Recent changes made clippy flag this parameter as unused.
2026-03-30 04:56:26 -04:00
Trevor Gross
1a5220e61d libm: Move tests out of generic to the consuming module
Make it easier for us to test both the generic and type-specific
versions of functions at once.
2026-03-30 04:56:26 -04:00
Trevor Gross
b8ee2ff860 etc: Search for *_status and *_round functions
Account for function definitions in `generic` that have one of our
standard suffixes in the API searcher.
2026-03-30 04:56:26 -04:00
Jynn Nelson
6ea175cd05 Remove unused code 2026-03-30 07:56:16 +00:00
Trevor Gross
bf73d7c9fe libm: Reorder functions in arch/ from smallest to largest type
Make this module consistent with other areas of code containing multiple
types.
2026-03-30 02:32:41 -04:00
Trevor Gross
d11c9f69fb libm: Split files in arch/
Split functions across files so `arch/` closer mirrors the top-level
`math` directory. Similar operations are still kept in the same file
since many of these functions are pretty tiny.

This will make it a bit easier to extend assembly implementations
without winding up with cluttered files, and helps avoid false positives
in the ci-util.py checks for changed operations.
2026-03-30 02:32:41 -04:00
Trevor Gross
220bcdaee7 libm: Prepare to split files in arch/
Move arch-specific files to an arch-named directory with a name based on
whatever most of the operations in the file are, in preparation for
splitting the file up. Moving to these names in a separate commit is
done as a git hack to keep as much of the blame intact as possible,
without needing `-M` or `-C`.

Note that libm does not build after this commit. The next commit
resolves this.
2026-03-30 02:32:41 -04:00
Trevor Gross
855bc875ec test: Add a number of specific test cases
Most of these come from the list at [1], or from failures collected when
updating test precision.

[1]: https://github.com/rust-lang/compiler-builtins/issues/836
2026-03-29 22:52:39 -04:00
Trevor Gross
ef7d030120 test: Allow special case overrides for list tests
Currently an exact xfail result is needed on platforms that have variability
(i586) but this is awkward to work with, especially for bessel
functions. Change this to allow `SpecialCase` to be used.
2026-03-29 22:52:39 -04:00
Trevor Gross
2b76b8eae8 test: Update precision defaults to be more accurate
The current flow is somewhat confusing in what is an inaccuracy due to
musl (either from implementation or from problems in the C ABI that we
avoid) and what is an inaccuracy in our library on specific platforms.
Clean up the structure here, which allows for some more narrow bounds.
2026-03-29 22:52:39 -04:00
Trevor Gross
bd2b448e08 test: Introduce a cases! macro for adding specific test cases 2026-03-29 22:52:39 -04:00
Trevor Gross
5e472e625d util: Allow a trailing comma for operands
Make it easier to copy test output when evaluating multi-input
functions.
2026-03-29 22:52:39 -04:00
Michael Howell
bfaf027a3b rustdoc: include index-page in dep-info 2026-03-29 19:25:50 -07:00
Trevor Gross
6dc3b2680c ci: Remove wall time benchmarks from CI
The icount benchmarks are significantly more reliable, and I don't think
these results get looked at too much. They can be run locally if needed,
so save the CI time here.
2026-03-27 20:32:21 -04:00
Trevor Gross
d7f20a9267 ci: Add benchmarks for i686
This is one arch that is reasonably easy to set up without native
runners, and gives us an idea of how the crates do on 32-bit platforms.
2026-03-27 20:32:21 -04:00
Trevor Gross
d7f6c3d777 ci: Add a retry to the compiler-rt download 2026-03-27 18:02:47 -04:00
Ana Hobden
72825b9934 Mark code only used in nightly as nightly only 2026-03-27 13:24:09 -07:00
Trevor Gross
7332ac06c0 api-list: Move sort and unique checks to tests
Having them as part of the `LazyLock` means that if something is
unsorted, the macro panics and produces a lot of warnings. Move these to
a test instead.
2026-03-27 07:29:27 -04:00
Trevor Gross
b6d05f5993 test: Move libm-macros/shared.rs to a new api-list-common crate
This file is already used in two places and was going to be needed in
another. Turning it into its own crate makes things easier to work with,
and allows for the removal of a few `allow(dead_code)` instances.
2026-03-27 07:29:27 -04:00
Brian Cain
8ada24abbf Add support for Hexagon HVX (#509)
* Add support for Hexagon HVX

Add vendor module and tests for Qualcomm Hexagon HVX (Hexagon Vector
eXtension) SIMD support. HVX provides wide vector operations in either
64-byte (512-bit) or 128-byte (1024-bit) mode.

Note: u8x128/i8x128 types are not included because portable-simd
currently limits lane count to 64 (bitmask operations use u64).
In 128-byte HVX mode, u8x64 maps to a half-vector (512-bit).

* fixup! Add support for Hexagon HVX

fixup! Add support for Hexagon HVX

Address reviewer feedback:
- Remove hexagon_hvx test file (existing tests suffice with -C flags)
- Move HvxVector imports into their respective cfg modules
- Change u8x128/i8x128 comment to FIXME for discoverability
2026-03-27 00:06:02 -04:00
linshuy2
be6cf3c9af Apply question_mark to Clippy itself 2026-03-26 21:34:11 +00:00
linshuy2
cfd67fc313 fix: question_mark FN for manual unwrap with if let 2026-03-26 21:33:45 +00:00
Vadim Petrochenkov
b0b1ebe636 resolve: Remove a special case for dummy imports
It is no longer needed to pass import validation, and the removal avoids some secondary errors.

Also add a couple of asserts
2026-03-26 21:11:33 +03:00
Vadim Petrochenkov
7559c2c14a resolve: Avoid using best_decl in try_plant_decl_into_local_module
Using `self.(non_)glob_decl` directly makes it more clear.
2026-03-26 20:35:43 +03:00
linshuy2
72e7f28a3c fix: question_mark FN when match binding is behind ref or mut 2026-03-26 17:24:52 +00:00
linshuy2
fca46564b0 fix: question_mark FN when the match scrutinee is behind reference 2026-03-26 17:07:06 +00:00
linshuy2
7c6ac13706 fix: question_mark FN for manual unwrap with match 2026-03-26 17:04:05 +00:00
ginnyTheCat
a227bc7ee9 Make std::fs::File Send on UEFI 2026-03-26 17:42:08 +01:00
Vadim Petrochenkov
5b84ee80eb resolve: Avoid using best_decl in NameResolution::determined_decl
Using `self.(non_)glob_decl` directly makes it more clear.
2026-03-26 19:38:14 +03:00
Vadim Petrochenkov
c6cb2cc851 resolve: Rename NameResolution::binding to determined_decl
Avoid two of its uses in diagnostic reporting and effective visibility collection.
The method is only supposed to be used inside the import resolution algorithm, and the removed uses happened after import resolution already converged.

Some comments are also added.
2026-03-26 19:38:14 +03:00
Amanieu d'Antras
f8369e3d47 Merge pull request #2065 from heiher/loong-inline-always
Mark the LoongArch intrinsics as inline(always)
2026-03-26 11:09:23 +00:00
Alejandra Gonzalez
1437b428ba perf: disable nonminimal_bool by default
After performance concers on the `nonminimal_bool` lint, we performed a
crater run (rust-lang/rust issue number 153883).

This crater run revealed that in 19120 suggestions taken from 1.3
million crates, only about 36% had resulted in multi-terminal
suggestions (suggestions that were not only a single boolean).

This suggests that most cases of this lint firing, the expression that
triggered was pretty simple. And thus, we should not take such a huge
toll for a lint that isn't that useful.

changelog:[`nonminimal_bool`]: Move to `pedantic`.
changelog:[`overly_complex_bool_expr`]: Move to `pedantic`.
2026-03-26 00:32:49 +01:00
Sayantan Chakraborty
1eafc19acd Merge pull request #2041 from ArunTamil21/add-alias-tests
Add missing runtime tests for SSE alias intrinsics
2026-03-25 18:19:10 +00:00
Trevor Gross
378a812d5e test: Switch to gungraun's new macro syntax 2026-03-25 09:44:48 -04:00
Trevor Gross
693662d760 test: Add new functions to icount benchmarks 2026-03-25 09:44:48 -04:00
Trevor Gross
c80dab6679 test: Cover compiler-builtins integer arithmetic in libm-test
Add the following to the test infrastructure:

* `__rust_i128_add`
* `__rust_i128_sub`
* `__rust_u128_add`
* `__rust_u128_sub`
* `__rust_i128_addo`
* `__rust_i128_subo`
* `__rust_u128_addo`
* `__rust_u128_subo`
* `__muldi3`
* `__multi3`
* `__mulosi4`
* `__mulodi4`
* `__muloti4`
* `__rust_u128_mulo`
* `__divsi3`
* `__divdi3`
* `__divti3`
* `__modsi3`
* `__moddi3`
* `__modti3`
* `__divmodsi4`
* `__divmoddi4`
* `__divmodti4`
* `__udivsi3`
* `__udivdi3`
* `__udivti3`
* `__umodsi3`
* `__umoddi3`
* `__umodti3`
* `__udivmodsi4`
* `__udivmoddi4`
* `__udivmodti4`
2026-03-25 07:52:22 -04:00
Trevor Gross
6ff91b0470 test: Cover compiler-builtins integer bit ops in libm-test
Add the following to the test infrastructure:

* `__ashlsi3`
* `__ashldi3`
* `__ashlti3`
* `__ashrsi3`
* `__ashrdi3`
* `__ashrti3`
* `__lshrsi3`
* `__lshrdi3`
* `__lshrti3`
* `__clzsi2`
* `__clzdi2`
* `__clzti2`
* `__ctzsi2`
* `__ctzdi2`
* `__ctzti2`
2026-03-25 06:25:29 -04:00
Trevor Gross
3135979797 test: Cover compiler-builtins int to float conversion in libm-test
Add the following to the test infrastructure:

* `itof_i32_f32`
* `itof_i64_f32`
* `itof_i128_f32`
* `itof_i32_f64`
* `itof_i64_f64`
* `itof_i128_f64`
* `itof_i32_f128`
* `itof_i64_f128`
* `itof_i128_f128`
* `itof_u32_f32`
* `itof_u64_f32`
* `itof_u128_f32`
* `itof_u32_f64`
* `itof_u64_f64`
* `itof_u128_f64`
* `itof_u32_f128`
* `itof_u64_f128`
* `itof_u128_f128`
2026-03-25 04:53:48 -04:00
Trevor Gross
d713b422f1 test: Remove FTy from libm-test traits
Now that tests have moved to using argument types instead of a whole-
function float type, remove `FTy` and its relevant configuration. This
will make it possible to use the same infrastructure for functions that
don't have any floats as arguments, or don't have any at all.

Some uses of `FTy` have been replaced with the `Group` enum, e.g. for
match arm patterns and selecting extensive tests. Anything that doesn't
have float types in the signature will be in the `Integer` category.
2026-03-25 03:06:05 -04:00
Trevor Gross
495d1e84ec test: Migrate from using FTy to accessing individual arguments
We can always access individual arguments rather than relying on the
common `FTy` type. This is a cleaner design anyway since it handles
functions with integers in the signature better.
2026-03-25 03:06:05 -04:00
Trevor Gross
383ddd118d test: Introduce a helper trait for tuple type access
Make it possible to access each argument without relying on `FTy`.
2026-03-25 03:06:05 -04:00
Trevor Gross
0adf2b3b24 test: Move the math_op function out of macro code
There isn't anything special about its implementation, so make it normal
code to clean some things up.
2026-03-25 03:06:05 -04:00
Michael Howell
a15a3d15b7 rustdoc: loaded files in dep-info for standalone 2026-03-24 22:55:36 -07:00
Michael Howell
e5ec5e2632 rustdoc: dep-info for standalone markdown inputs 2026-03-24 22:37:59 -07:00
Bo YU
90bb1f20b8 ci: use CARGO_TARGET_DIR instead of .dockerenv for nextest config
The .dockerenv check was a workaround for Docker CI where the
checkout is mounted read-only. However, its presence does not reliably
indicate that the filesystem is unwritable.

Use CARGO_TARGET_DIR as the condition instead, which directly
captures when a custom writable target directory is in use and avoids
false assumptions.
2026-03-24 13:49:26 -04:00
ArunTamil21
30573344b0 Mark alias test wrappers as const fn where supported and clean up skip list 2026-03-24 12:23:05 +00:00
Trevor Gross
4303aa9350 test: Cover compiler-builtins float to int conversion in libm-test
Add the following to the test infrastructure:

* `__fixdfdi`
* `__fixdfsi`
* `__fixdfti`
* `__fixsfdi`
* `__fixsfsi`
* `__fixsfti`
* `__fixtfdi`
* `__fixtfsi`
* `__fixtfti`
* `__fixunsdfdi`
* `__fixunsdfsi`
* `__fixunsdfti`
* `__fixunssfdi`
* `__fixunssfsi`
* `__fixunssfti`
* `__fixunstfdi`
* `__fixunstfsi`
* `__fixunstfti`
2026-03-24 05:38:53 -04:00
Trevor Gross
f4df517593 test: Strip multiple suffixes when computing the base name
This allows us to use a single base name for functions that have
multiple types in the signature, such as `extend_f32_f64`.

The compiler-builtins `trunc` operation wrappers had to be renamed to
`narrow` to avoid conflicting with libm `trunc`.
2026-03-24 05:38:53 -04:00
Trevor Gross
5650d0829d test: Consolidate Hexf, Hexi, and the Hex trait
Create a new struct `Hex` that serves all of these purposes via a new
trait `DisplayHex`. This is easier to work with because we can make
`DisplayHex` a bound of `Float`.
2026-03-24 05:38:53 -04:00
Trevor Gross
3cef40c882 test: Add benchmarks for c-b functions covered in libm-test
Wire up benchmarks for functions that are now part of our testing
infrastructure.
2026-03-24 03:55:32 -04:00
Trevor Gross
456bf77218 macros: Update skip_f16_f128 to handle return types 2026-03-24 02:58:40 -04:00
Trevor Gross
3e16dd3ec4 test: Cover compiler-builtins float conversion in libm-test
Add the following to the test infrastructure:

* `__extenddftf2`
* `__extendhfdf2`
* `__extendhfsf2`
* `__extendhftf2`
* `__extendsfdf2`
* `__extendsftf2`
* `__truncdfhf2`
* `__truncdfsf2`
* `__truncsfhf2`
* `__trunctfdf2`
* `__trunctfhf2`
* `__trunctfsf2`
2026-03-24 02:58:40 -04:00
lms0806
ac5e448d23 resolve : issue 154034
resolve :  mark repr_simd as internal

resolve : move repr_simd

resolve : move repr_simd
under linkage

resolve : move repr_simd
under pattern_types

resolve :  mark repr_simd as internal

resolve : move repr_simd

resolve : move repr_simd
under linkage

resolve : move repr_simd
under pattern_types
2026-03-24 15:56:55 +09:00
Trevor Gross
178cea5dae test: Cover compiler-builtins float comparison in libm-test
Add the following to our larger test infrastructure:

* `__eq[hsdf]2`
* `__ne[hsdf]2`
* `__unord[hsdf]2`
* `__lt[hsdf]2`
* `__le[hsdf]2`
* `__gt[hsdf]2`
* `__ge[hsdf]2`
2026-03-24 01:17:42 -04:00
Trevor Gross
b6331ad631 test: Clean up macro use in builtins_wrappers 2026-03-24 01:17:42 -04:00
Trevor Gross
e8e3bdd6b7 test: Better support tests that don't require a ulp value 2026-03-24 01:17:42 -04:00
Trevor Gross
5ac939394a ci: Move matrix.os comparisons to an environment variable 2026-03-24 00:40:41 -04:00
Trevor Gross
16cb48102c meta: Cover both .yaml and .yml in .editorconfig 2026-03-24 00:40:41 -04:00
Trevor Gross
d3e8724f25 test: Use the libm testing infra to test compiler-builtins
Add wrappers for compiler-builtins that closer match the libm
interfaces, and add basic compiler-builtins float arithmetic to the set
of tested functions.

This means we now get tests against MPFR, better edge case coverage,
extensive testing, and benchmarks for the following functions:

* `__add[hsdt]f3`
* `__sub[hsdt]f3`
* `__mul[hsdt]f3`
* `__div[sdt]f3`
* `__powi[sdt]f2`

Functions from compiler-builtins have not yet been tied in with
`update-api-list.py` and the CI tooling that reads it, that will need to
be updated in a follow up.
2026-03-23 21:43:18 -04:00
linshuy2
e1b713ab09 fix: expect_fun_call suggests wrongly for string slicing 2026-03-23 17:33:24 +00:00
vimer
ca309a4015 ci: Test on riscv64 using a self-hosted runner
Closes: https://github.com/rust-lang/compiler-builtins/issues/1054
2026-03-23 11:54:58 -05:00
Bo YU
43b30e82bc ci: update nextest to 0.9.131 with install-action 2026-03-23 12:05:11 -04:00
linshuy2
ede468a7b8 fix: let_and_return wrongly unmangles macros 2026-03-23 02:31:48 +00:00
Linshu Yang
ab427a2236 fix: manual_swap wrongly unmangled macros 2026-03-23 02:31:48 +00:00
Linshu Yang
a407005471 fix: range_minus_one and range_plus_one wrongly unmangled macros 2026-03-23 02:31:48 +00:00
Linshu Yang
838e235b2d fix: implicit_saturating_sub wrongly unmangled macros 2026-03-23 02:31:48 +00:00
Linshu Yang
93bf95b230 fix: manual_div_ceil wrongly unmangled macros 2026-03-23 02:31:45 +00:00
Linshu Yang
31f04c7098 fix: manual_is_power_of_two wrongly unmangled macros 2026-03-23 02:09:43 +00:00
Linshu Yang
3272a9b557 fix: needless_bool wrongly unmangled macros 2026-03-23 02:09:43 +00:00
Linshu Yang
a255ac1d82 fix: map_with_unused_argument_over_ranges wrongly unmangled macros 2026-03-23 02:07:09 +00:00
Linshu Yang
d3ca65d04a fix: manual_rotate wrongly unmangled macros 2026-03-22 23:43:38 +00:00
Trevor Gross
74955ac95c libm: Remove hexu in favor of formatting traits on u256
Use the same trick as with other formatting implementations, which makes
it possible to get rid of the awkward `-> String` functions.
2026-03-22 17:27:23 -04:00
ArunTamil21
2c76cb3479 Use const fn and remove unsafe from alias test wrappers 2026-03-22 19:50:07 +00:00
Sayantan Chakraborty
93c4d0ad6e Merge pull request #2064 from ferrocene/jyn/docs
Add more docs on how to run the generator
2026-03-21 17:56:41 +00:00
Juho Kahala
d552a7cd70 libm: fix test for overflow in u256::shr 2026-03-20 12:35:01 -04:00
Jynn Nelson
dc3ba83196 Add more docs on how to run the generator
- Note that working directory matters
- Note that stdarch-gen-arm uses nightly
- Fix missing directory. Without this, it would print to stdout in one
  giant merged file.
2026-03-19 13:43:40 +01:00
WANG Rui
9adc2b00fc Mark the LoongArch intrinsics as inline(always) 2026-03-19 20:41:22 +08:00
Caleb Zulawski
0c17257b6a Merge pull request #514 from folkertdev/toolchain-bump
bump toolchain to `nightly-2026-03-18`
2026-03-18 20:15:55 -04:00
Folkert de Vries
ed150fbd5b bump toolchain to nightly-2026-03-18 2026-03-18 22:06:36 +01:00
ArunTamil21
7da5fbcf42 Fix formatting 2026-03-17 22:18:40 +00:00
ArunTamil21
68a6acef71 Use macros for test body deduplication in SSE alias tests 2026-03-17 22:16:33 +00:00
Trevor Gross
41a6f3e24e ci: Resolve audit issues reported by zizmore
Resolve two cases of `ref-version-mismatch` and various `artipacked`
instances.
2026-03-17 11:09:56 -04:00
Bo YU
741b5e93cd Add zizmor to check Github Actions (static analysis) 2026-03-17 10:26:19 -04:00
Trevor Gross
549b6d708d ci: Add configuration for renovatebot (#1114)
Based on the configuration for bors [1].

[1]: d89bfc24e8/.github/renovate.json5
2026-03-17 14:25:37 +00:00
Trevor Gross
51eea03cf8 ci: Resolve audit issues reported by zizmore
Resolve the following lints:

* `unpinned-uses`: Pin action versions using `zizmor --fix`
* `excessive-permissions`: Add `permissions: {}` to all workflows
* `template-injection`: This one wasn't too concerning since `${{ ...
  }}` was only used for `matrix` and `needs` access, but it is easy
  enough to resolve by storing in an environment variable.
2026-03-17 10:22:00 -04:00
Marco Ieni
7e44508eee Merge pull request #1112 from marcoieni/publish-via-trusted-publishing
publish via trusted publishing
2026-03-17 10:25:37 +01:00
Trevor Gross
d723253b19 Revert "ci: Pin Miri to the 2026-02-11 nightly"
The described issue in the reverted commit is no longer relevant.

This reverts commit 870ab266bad7ec0a56abfc433f92e3c2d67a572c.
2026-03-16 14:11:58 -05:00
Folkert de Vries
f6382501f9 export __mulsi3 on m68k 2026-03-16 13:30:53 -05:00
Martin Nordholts
686ddd3e2e tests/debuginfo/basic-stepping.rs: Explain why all lines are not steppable
Some optimization passes _improve_ compile times [1]. So we want to run
some passes even with `-Copt-level=0`. That means that some of the lines
in the test can be optimized away. To make regression testing more
robust, we also want to run the test with such passes disabled. The
solution is to use two revisions. One with default `-Copt-level=0`
passes, and one "even less optimized", with enough optimization passes
disabled to keep the maximum number of lines steppable.

[1]: https://github.com/rust-lang/compiler-team/issues/319
2026-03-16 18:39:40 +01:00
MarcoIeni
8d51ad1eac publish via trusted publishing 2026-03-16 17:26:40 +01:00
Trevor Gross
7463a85ad0 ci: Bump all actions to latest 2026-03-15 17:30:46 -05:00
Caleb Zulawski
99e9d40db5 Merge pull request #510 from zRedShift/add-round-ties-even
Add round_ties_even to StdFloat trait
2026-03-15 11:02:31 -04:00
Folkert de Vries
ee9b61cf75 deprecate std::char constants and functions
similar to how constants in those modules for numeric types have been deprecated
2026-03-15 11:18:22 +01:00
Caleb Zulawski
3bc9bcfd61 Merge pull request #512 from Kmeakin/km/simd-first-set
Optimize `mask::first_set`
2026-03-14 17:28:12 -04:00
Caleb Zulawski
7d6df680c1 Merge pull request #511 from folkertdev/update-proptest
update `proptest` from `0.10` to `1.0`
2026-03-14 14:47:45 -04:00
Karl Meakin
b99b62c2d9 Optimize Mask::first_set
Apply two optimizations to `Mask::first_set`:

1) Move the call to `simd_cast` into the `const` block when initializing
   `index`. This removes runtime shuffles necessary to translate a
   `Simd<usize, N>` to a `Simd<T, N>`.

2) Replace the call to `mask.select` with `simd_or(!self, index)`. This
   is cheaper than doing a comparison and on some architectures the `or`
   can be combined with the `not` into a single instruction.

See https://godbolt.org/z/YebG6aoMY for an example of the difference in
generated assembly.
2026-03-14 18:38:27 +00:00
Karl Meakin
5c37faf35c Add tests for Mask::first_set
Add exhuastive tests for `Mask::first_set` for all masks of size 8.
2026-03-14 18:37:21 +00:00
Folkert de Vries
dc5ab0d049 update proptest from 0.10 to 1.0 2026-03-14 16:20:38 +01:00
ArunTamil21
0eb04eb555 Fix formatting 2026-03-12 13:16:36 +00:00
ArunTamil21
ec448dd82a Merge upstream/main and resolve conflict in x86-intel.rs 2026-03-12 13:14:30 +00:00
ArunTamil21
58e5c0e879 Refactor alias tests using macros instead of meta functions 2026-03-12 13:01:57 +00:00
arferreira
4d3f0db260 Deprioritize doc(hidden) re-exports in diagnostic paths 2026-03-09 18:31:29 -04:00
Taiki Endo
e0d9940c1e rustc_codegen_ssa: Define ELF flag value for sparc-unknown-linux-gnu 2026-03-07 21:53:18 +09:00
Daniel Scherzer
d218e7fa30 std::any::TypeId: remove misplaced "and" in Unique<T> example 2026-03-06 10:24:45 -08:00
CoCo-Japan-pan
fae6a311e7 Add UI tests for inherent associated item import attempts 2026-03-05 20:09:33 +09:00
CoCo-Japan-pan
4d5ce5ddab Add note for enum import errors when import_trait_associated_functions is enabled 2026-03-05 20:08:21 +09:00
CoCo-Japan-pan
58374d7a9e Modify the error message shown when a user tries to import inherent associated items 2026-03-05 20:07:18 +09:00
ArunTamil21
952302abac Remove redundant tests for _mm_prefetch and _mm_undefined_ps
Already verified by assert_instr; no output to assert at runtime.
2026-02-27 18:28:23 +00:00
ArunTamil21
455b21ba99 Restore deleted test_mm_store_ps 2026-02-26 16:27:41 +00:00
ArunTamil21
63fb6c3c59 Refactor alias tests using meta function pattern and add missing tests for _mm_undefined_ps, _mm_prefetch, _mm_load_ps1, _mm_store_ps1 2026-02-26 16:18:30 +00:00
ArunTamil21
580a179bbe Add missing runtime tests for alias intrinsics: _mm_cvt_ss2si, _mm_cvtt_ss2si, _mm_cvt_si2ss, _mm_set_ps1 2026-02-26 14:45:42 +00:00
Ronen Ulanovsky
e66819d2cf Add round_ties_even to StdFloat trait
Adds `round_ties_even` using `simd_round_ties_even` intrinsic, matching
the scalar `f32::round_ties_even` / `f64::round_ties_even` API.

Closes rust-lang/portable-simd#390
2026-02-21 20:01:22 +02:00
Ayush Singh
47bec22de1 std: sys: process: uefi: Add program searching
- Follow UEFI Shell search flow to search for programs while launching.
- Tested using OVMF on QEMU.

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
2026-02-17 10:50:35 +05:30
Jacob Lifshay
b8bef675f7 Merge pull request #508 from him2him2/fix-typos
Fix typos in documentation
2026-02-10 09:39:53 -08:00
ron
af5171205f Fix typos in documentation
- beginners-guide.md: fix missing letter ("within you" → "within your")
- .github/PULL_REQUEST_TEMPLATE.md: remove duplicate word ("tests for test interactions" → "tests for interactions")
2026-02-10 10:50:42 -05:00
Jacob Lifshay
b6a0170077 Merge pull request #507 from b01o/fix-doc-simd-load-select-or-default
docs(simd): fix `load_select_or_default` documentation
2026-02-07 23:53:20 -08:00
b01o
81dcf4c4a8 more clear example 2026-02-08 15:28:29 +08:00
b01o
08aa04d7aa show both kinds of masking-out elements in the example 2026-02-08 15:13:17 +08:00
b01o
a8af194738 docs(simd): fix load_select_or_default documentation 2026-02-08 13:37:49 +08:00
Jacob Lifshay
e797bc719d Merge pull request #506 from okaneco/prelude
Add `Select` and `ToBytes` to prelude
2026-02-07 20:10:49 -08:00
okaneco
01f91e468c Add Select and ToBytes to prelude 2026-02-07 15:53:29 -05:00
Caleb Zulawski
bad79308df Merge pull request #504 from Urgau/triagebot-config
Add basic triagebot configuration
2026-01-29 13:11:22 -05:00
Urgau
0e4bebafa9 Add basic triagebot configuration 2026-01-29 18:27:54 +01:00
Marijn Schouten
3a9981a6d5 clippy fix: non_canonical_clone_impl (except Infallible) 2026-01-27 13:00:35 +00:00
dianqk
23ec2cf068 Revert "Add a workaround for the TailDuplicator compile time overhead"
This reverts commit 2884230df2.
2026-01-23 18:39:32 +08:00
dianqk
cae926b5de Revert "Remove restrictions on small enum statements such as Order, Option or Result"
This reverts commit 102bda49b1.
2026-01-23 18:36:50 +08:00
Flakebi
842c087427 Fix requires_lto targets needing lto set in cargo
Targets that set `requires_lto = true` were not actually using lto when
compiling with cargo by default. They needed an extra `lto = true` in
`Cargo.toml` to work.

Fix this by letting lto take precedence over the `embed_bitcode` flag
when lto is required by a target.

If both these flags would be supplied by the user, an error is
generated. However, this did not happen when lto was requested by the
target instead of the user.
2025-12-29 21:56:52 +01:00
Taiki Endo
0e452d4d10 fn_to_numeric_cast_any: Do not warn cast to raw pointer 2025-12-27 16:31:31 +09:00
3623 changed files with 390316 additions and 48864 deletions

2
.gitmodules vendored
View File

@@ -25,7 +25,7 @@
[submodule "src/llvm-project"]
path = src/llvm-project
url = https://github.com/rust-lang/llvm-project.git
branch = rustc/22.1-2026-01-27
branch = rustc/22.1-2026-03-22
shallow = true
[submodule "src/doc/embedded-book"]
path = src/doc/embedded-book

View File

@@ -258,11 +258,11 @@ Greg V <greg@unrelenting.technology>
Gregor Peach <gregorpeach@gmail.com>
Grzegorz Bartoszek <grzegorz.bartoszek@thaumatec.com>
Guanqun Lu <guanqun.lu@gmail.com>
Guillaume Gomez <guillaume1.gomez@gmail.com>
Guillaume Gomez <guillaume1.gomez@gmail.com> ggomez <ggomez@ggo.ifr.lan>
Guillaume Gomez <guillaume1.gomez@gmail.com> Guillaume Gomez <ggomez@ggo.ifr.lan>
Guillaume Gomez <guillaume1.gomez@gmail.com> Guillaume Gomez <guillaume.gomez@huawei.com>
Guillaume Gomez <guillaume1.gomez@gmail.com> Guillaume Gomez <contact@guillaume-gomez.fr>
Guillaume Gomez <contact@guillaume-gomez.fr>
Guillaume Gomez <contact@guillaume-gomez.fr> Guillaume Gomez <guillaume1.gomez@gmail.com>
Guillaume Gomez <contact@guillaume-gomez.fr> ggomez <ggomez@ggo.ifr.lan>
Guillaume Gomez <contact@guillaume-gomez.fr> Guillaume Gomez <ggomez@ggo.ifr.lan>
Guillaume Gomez <contact@guillaume-gomez.fr> Guillaume Gomez <guillaume.gomez@huawei.com>
gnzlbg <gonzalobg88@gmail.com> <gnzlbg@users.noreply.github.com>
hamidreza kalbasi <hamidrezakalbasi@protonmail.com>
Hanna Kruppe <hanna.kruppe@gmail.com> <robin.kruppe@gmail.com>

View File

@@ -199,7 +199,7 @@ dependencies = [
"rustc-hash 2.1.1",
"serde",
"serde_derive",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -257,7 +257,7 @@ dependencies = [
"miniz_oxide",
"object 0.36.7",
"rustc-demangle",
"windows-targets 0.52.6",
"windows-targets",
]
[[package]]
@@ -396,7 +396,7 @@ checksum = "89385e82b5d1821d2219e0b095efa2cc1f246cbf99080f3be46a1a85c0d392d9"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -573,7 +573,6 @@ checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2"
dependencies = [
"iana-time-zone",
"num-traits",
"serde",
"windows-link 0.2.1",
]
@@ -635,10 +634,10 @@ version = "4.5.49"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a0b5487afeab2deb2ff4e03a807ad1a03ac532ff5a2cee5d86884440c7f7671"
dependencies = [
"heck 0.5.0",
"heck",
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -649,11 +648,11 @@ checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d"
[[package]]
name = "clippy"
version = "0.1.96"
version = "0.1.97"
dependencies = [
"anstream",
"askama",
"cargo_metadata 0.18.1",
"cargo_metadata 0.23.1",
"clippy_config",
"clippy_lints",
"clippy_lints_internal",
@@ -676,7 +675,7 @@ dependencies = [
[[package]]
name = "clippy_config"
version = "0.1.96"
version = "0.1.97"
dependencies = [
"clippy_utils",
"itertools",
@@ -700,10 +699,10 @@ dependencies = [
[[package]]
name = "clippy_lints"
version = "0.1.96"
version = "0.1.97"
dependencies = [
"arrayvec",
"cargo_metadata 0.18.1",
"cargo_metadata 0.23.1",
"clippy_config",
"clippy_utils",
"declare_clippy_lint",
@@ -732,7 +731,7 @@ dependencies = [
[[package]]
name = "clippy_utils"
version = "0.1.96"
version = "0.1.97"
dependencies = [
"arrayvec",
"itertools",
@@ -757,7 +756,7 @@ checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
dependencies = [
"serde",
"termcolor",
"unicode-width 0.2.2",
"unicode-width 0.1.14",
]
[[package]]
@@ -768,7 +767,6 @@ dependencies = [
"serde",
"serde_json",
"similar",
"spdx-rs",
]
[[package]]
@@ -804,7 +802,7 @@ dependencies = [
"nom",
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -827,21 +825,11 @@ checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
[[package]]
name = "colored"
version = "2.2.0"
version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"
dependencies = [
"lazy_static",
"windows-sys 0.59.0",
]
[[package]]
name = "colored"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -857,7 +845,7 @@ dependencies = [
"anstyle-svg",
"build_helper",
"camino",
"colored 2.2.0",
"colored",
"diff",
"getopts",
"glob",
@@ -881,15 +869,14 @@ dependencies = [
[[package]]
name = "console"
version = "0.15.11"
version = "0.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8"
checksum = "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87"
dependencies = [
"encode_unicode",
"libc",
"once_cell",
"unicode-width 0.2.2",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -1047,7 +1034,7 @@ dependencies = [
"proc-macro2",
"quote",
"scratch",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -1061,7 +1048,7 @@ dependencies = [
"indexmap",
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -1079,7 +1066,7 @@ dependencies = [
"indexmap",
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -1103,7 +1090,7 @@ dependencies = [
"proc-macro2",
"quote",
"strsim",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -1114,7 +1101,7 @@ checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
dependencies = [
"darling_core",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -1123,20 +1110,9 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0afaad2b26fa326569eb264b1363e8ae3357618c43982b3f285f0774ce76b69"
[[package]]
name = "dbus"
version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "190b6255e8ab55a7b568df5a883e9497edc3e4821c06396612048b430e5ad1e9"
dependencies = [
"libc",
"libdbus-sys",
"windows-sys 0.59.0",
]
[[package]]
name = "declare_clippy_lint"
version = "0.1.96"
version = "0.1.97"
[[package]]
name = "derive-where"
@@ -1146,7 +1122,7 @@ checksum = "d08b3a0bcc0d079199cd476b2cae8435016ec11d1c0986c6901c5ac223041534"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -1167,7 +1143,7 @@ dependencies = [
"darling",
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -1177,7 +1153,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"
dependencies = [
"derive_builder_core",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -1189,7 +1165,7 @@ dependencies = [
"darling",
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -1264,7 +1240,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -1404,14 +1380,13 @@ dependencies = [
[[package]]
name = "filetime"
version = "0.2.26"
version = "0.2.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc0505cd1b6fa6580283f6bdf70a73fcf4aba1184038c90902b92b3dd0df63ed"
checksum = "f98844151eee8917efc50bd9e8318cb963ae8b297431495d3f758616ea5c57db"
dependencies = [
"cfg-if",
"libc",
"libredox",
"windows-sys 0.60.2",
]
[[package]]
@@ -1678,10 +1653,13 @@ dependencies = [
]
[[package]]
name = "heck"
version = "0.4.1"
name = "hashbrown"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"
dependencies = [
"foldhash 0.2.0",
]
[[package]]
name = "heck"
@@ -1953,26 +1931,26 @@ checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5"
[[package]]
name = "indexmap"
version = "2.13.0"
version = "2.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
dependencies = [
"equivalent",
"hashbrown 0.16.1",
"hashbrown 0.17.0",
"serde",
"serde_core",
]
[[package]]
name = "indicatif"
version = "0.17.11"
version = "0.18.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235"
checksum = "25470f23803092da7d239834776d653104d551bc4d7eacaf31e6837854b8e9eb"
dependencies = [
"console",
"number_prefix",
"portable-atomic",
"unicode-width 0.2.2",
"unit-prefix",
"web-time",
]
@@ -2083,7 +2061,7 @@ checksum = "980af8b43c3ad5d8d349ace167ec8170839f753a42d233ba19e08afe1850fa69"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -2180,16 +2158,6 @@ version = "0.2.183"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d"
[[package]]
name = "libdbus-sys"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cbe856efeb50e4681f010e9aaa2bf0a644e10139e54cde10fc83a307c23bd9f"
dependencies = [
"cc",
"pkg-config",
]
[[package]]
name = "libffi"
version = "5.1.0"
@@ -2380,7 +2348,7 @@ checksum = "88a9689d8d44bf9964484516275f5cd4c9b59457a6940c1d5d0ecbb94510a36b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -2483,7 +2451,7 @@ dependencies = [
"capstone",
"chrono",
"chrono-tz",
"colored 3.0.0",
"colored",
"directories",
"genmc-sys",
"getrandom 0.3.3",
@@ -2525,7 +2493,7 @@ checksum = "4568f25ccbd45ab5d5603dc34318c1ec56b117531781260002151b8530a9f931"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -2657,12 +2625,6 @@ dependencies = [
"libc",
]
[[package]]
name = "number_prefix"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"
[[package]]
name = "objc2"
version = "0.6.3"
@@ -2749,14 +2711,13 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "opener"
version = "0.7.2"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0812e5e4df08da354c851a3376fead46db31c2214f849d3de356d774d057681"
checksum = "a2fa337e0cf13357c13ef1dc108df1333eb192f75fc170bea03fcf1fd404c2ee"
dependencies = [
"bstr",
"dbus",
"normpath",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -2906,7 +2867,7 @@ dependencies = [
"pest_meta",
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -3000,9 +2961,9 @@ dependencies = [
[[package]]
name = "portable-atomic"
version = "1.11.1"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483"
checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
[[package]]
name = "portable-atomic-util"
@@ -3116,7 +3077,7 @@ checksum = "7347867d0a7e1208d93b46767be83e2b8f978c3dad35f775ac8d8847551d6fe1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -3307,7 +3268,7 @@ checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -3400,7 +3361,7 @@ checksum = "8100bb34c0a1d0f907143db3149e6b4eea3c33b9ee8b189720168e818303986f"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -3806,7 +3767,7 @@ dependencies = [
"either",
"elsa",
"ena",
"hashbrown 0.16.1",
"hashbrown 0.17.0",
"indexmap",
"jobserver",
"libc",
@@ -3995,6 +3956,7 @@ dependencies = [
"rustc_ast_pretty",
"rustc_data_structures",
"rustc_error_messages",
"rustc_errors",
"rustc_hashes",
"rustc_hir_id",
"rustc_index",
@@ -4115,7 +4077,7 @@ version = "0.0.0"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -4261,7 +4223,7 @@ dependencies = [
"fluent-syntax",
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
"synstructure",
]
@@ -4569,7 +4531,6 @@ name = "rustc_query_impl"
version = "0.0.0"
dependencies = [
"measureme",
"rustc_abi",
"rustc_data_structures",
"rustc_errors",
"rustc_hir",
@@ -4843,7 +4804,7 @@ version = "0.0.0"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
"synstructure",
]
@@ -4943,7 +4904,7 @@ dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -5060,7 +5021,7 @@ dependencies = [
"proc-macro2",
"quote",
"serde_derive_internals",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -5146,7 +5107,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -5157,7 +5118,7 @@ checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -5271,12 +5232,12 @@ checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
[[package]]
name = "socket2"
version = "0.6.1"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881"
checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
dependencies = [
"libc",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -5290,35 +5251,6 @@ dependencies = [
"color-eyre",
]
[[package]]
name = "spdx-expression"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d7ac03c67c572d85049d6db815e20a4a19b41b3d5cca732ac582342021ad77"
dependencies = [
"nom",
"serde",
"thiserror 1.0.69",
"tracing",
]
[[package]]
name = "spdx-rs"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "990870190ec8d8c64ba66e4a6746243d6e57d99353991e0e6092334833f429b1"
dependencies = [
"chrono",
"log",
"nom",
"serde",
"spdx-expression",
"strum",
"strum_macros",
"thiserror 1.0.69",
"uuid",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -5384,36 +5316,6 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f"
[[package]]
name = "strum_macros"
version = "0.24.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59"
dependencies = [
"heck 0.4.1",
"proc-macro2",
"quote",
"rustversion",
"syn 1.0.109",
]
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "2.0.110"
@@ -5433,7 +5335,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -5540,9 +5442,9 @@ dependencies = [
[[package]]
name = "thin-vec"
version = "0.2.14"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "144f754d318415ac792f9d69fc87abbbfc043ce2ef041c60f16ad828f638717d"
checksum = "da322882471314edc77fa5232c587bcb87c9df52bfd0d7d4826f8868ead61899"
[[package]]
name = "thiserror"
@@ -5570,7 +5472,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -5581,7 +5483,7 @@ checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -5823,7 +5725,7 @@ checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -5956,9 +5858,9 @@ checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
[[package]]
name = "ui_test"
version = "0.30.3"
version = "0.30.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44eb652e1a8799d4e47f20851370e86247cbc5270ce677ab1e9409a6d45a9649"
checksum = "ada249620d81f010b9a1472b63a5077ac7c722dd0f4bacf6528b313d0b8c15d8"
dependencies = [
"annotate-snippets 0.11.5",
"anyhow",
@@ -5966,7 +5868,7 @@ dependencies = [
"cargo-platform 0.1.9",
"cargo_metadata 0.18.1",
"color-eyre",
"colored 3.0.0",
"colored",
"comma",
"crossbeam-channel",
"indicatif",
@@ -6019,7 +5921,7 @@ checksum = "a1249a628de3ad34b821ecb1001355bca3940bcb2f88558f1a8bd82e977f75b5"
dependencies = [
"proc-macro-hack",
"quote",
"syn 2.0.110",
"syn",
"unic-langid-impl",
]
@@ -6106,6 +6008,12 @@ dependencies = [
"diff",
]
[[package]]
name = "unit-prefix"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3"
[[package]]
name = "unstable-book-gen"
version = "0.1.0"
@@ -6257,7 +6165,7 @@ dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
"wasm-bindgen-shared",
]
@@ -6514,7 +6422,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -6525,7 +6433,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -6602,16 +6510,7 @@ version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
dependencies = [
"windows-targets 0.53.5",
"windows-targets",
]
[[package]]
@@ -6629,31 +6528,14 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm 0.52.6",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
name = "windows-targets"
version = "0.53.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
dependencies = [
"windows-link 0.2.1",
"windows_aarch64_gnullvm 0.53.1",
"windows_aarch64_msvc 0.53.1",
"windows_i686_gnu 0.53.1",
"windows_i686_gnullvm 0.53.1",
"windows_i686_msvc 0.53.1",
"windows_x86_64_gnu 0.53.1",
"windows_x86_64_gnullvm 0.53.1",
"windows_x86_64_msvc 0.53.1",
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
@@ -6680,96 +6562,48 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_aarch64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_i686_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "windows_x86_64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
[[package]]
name = "winnow"
version = "0.5.40"
@@ -6895,7 +6729,7 @@ checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
"synstructure",
]
@@ -6916,7 +6750,7 @@ checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]
@@ -6936,7 +6770,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
"synstructure",
]
@@ -6971,7 +6805,7 @@ checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.110",
"syn",
]
[[package]]

View File

@@ -1,3 +1,140 @@
Version 1.95.0 (2026-04-16)
===========================
<a id="1.95-Language"></a>
Language
--------
- [Stabilize `if let` guards on match arms](https://github.com/rust-lang/rust/pull/141295)
- [`irrefutable_let_patterns` lint no longer lints on let chains](https://github.com/rust-lang/rust/pull/146832)
- [Support importing path-segment keywords with renaming](https://github.com/rust-lang/rust/pull/146972)
- [Stabilize inline assembly for PowerPC and PowerPC64](https://github.com/rust-lang/rust/pull/147996)
- [const-eval: be more consistent in the behavior of padding during typed copies](https://github.com/rust-lang/rust/pull/148967)
- [Const blocks are no longer evaluated to determine if expressions involving fallible operations can implicitly be constant-promoted.](https://github.com/rust-lang/rust/pull/150557). Expressions whose ability to implicitly be promoted would depend on the result of a const block are no longer implicitly promoted.
- [Make operational semantics of pattern matching independent of crate and module](https://github.com/rust-lang/rust/pull/150681)
<a id="1.95-Compiler"></a>
Compiler
--------
- [Stabilize `--remap-path-scope` for controlling the scoping of how paths get remapped in the resulting binary](https://github.com/rust-lang/rust/pull/147611)
- [Apply patches for CVE-2026-6042 and CVE-2026-40200 to vendored musl](https://github.com/rust-lang/rust/pull/155171)
<a id="1.95-Platform-Support"></a>
Platform Support
----------------
- [Promote `powerpc64-unknown-linux-musl` to Tier 2 with host tools](https://github.com/rust-lang/rust/pull/149962)
- [Promote `aarch64-apple-tvos` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
- [Promote `aarch64-apple-tvos-sim` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
- [Promote `aarch64-apple-watchos` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
- [Promote `aarch64-apple-watchos-sim` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
- [Promote `aarch64-apple-visionos` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
- [Promote `aarch64-apple-visionos-sim` to Tier 2](https://github.com/rust-lang/rust/pull/152021)
Refer to Rust's [platform support page][platform-support-doc]
for more information on Rust's tiered platform support.
[platform-support-doc]: https://doc.rust-lang.org/rustc/platform-support.html
<a id="1.95-Libraries"></a>
Libraries
---------
- [`thread::scope`: document how join interacts with TLS destructors](https://github.com/rust-lang/rust/pull/149482)
- [Speed up `str::contains` on aarch64 targets with `neon` target feature enabled by default](https://github.com/rust-lang/rust/pull/152176)
<a id="1.95-Stabilized-APIs"></a>
Stabilized APIs
---------------
- [`MaybeUninit<[T; N]>: From<[MaybeUninit<T>; N]>`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#impl-From%3CMaybeUninit%3C%5BT;+N%5D%3E%3E-for-%5BMaybeUninit%3CT%3E;+N%5D)
- [`MaybeUninit<[T; N]>: AsRef<[MaybeUninit<T>; N]>`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#impl-AsRef%3C%5BMaybeUninit%3CT%3E;+N%5D%3E-for-MaybeUninit%3C%5BT;+N%5D%3E)
- [`MaybeUninit<[T; N]>: AsRef<[MaybeUninit<T>]>`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#impl-AsRef%3C%5BMaybeUninit%3CT%3E%5D%3E-for-MaybeUninit%3C%5BT;+N%5D%3E)
- [`MaybeUninit<[T; N]>: AsMut<[MaybeUninit<T>; N]>`](https://doc.rust-lang.org/beta/std/mem/union.MaybeUninit.html#impl-AsMut%3C%5BMaybeUninit%3CT%3E;+N%5D%3E-for-MaybeUninit%3C%5BT;+N%5D%3E)
- [`MaybeUninit<[T; N]>: AsMut<[MaybeUninit<T>]>`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#impl-AsMut%3C%5BMaybeUninit%3CT%3E%5D%3E-for-MaybeUninit%3C%5BT;+N%5D%3E)
- [`[MaybeUninit<T>; N]: From<MaybeUninit<[T; N]>>`](https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#impl-From%3C%5BMaybeUninit%3CT%3E;+N%5D%3E-for-MaybeUninit%3C%5BT;+N%5D%3E)
- [`Cell<[T; N]>: AsRef<[Cell<T>; N]>`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#impl-AsRef%3C%5BCell%3CT%3E;+N%5D%3E-for-Cell%3C%5BT;+N%5D%3E)
- [`Cell<[T; N]>: AsRef<[Cell<T>]>`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#impl-AsRef%3C%5BCell%3CT%3E%5D%3E-for-Cell%3C%5BT;+N%5D%3E)
- [`Cell<[T]>: AsRef<[Cell<T>]>`](https://doc.rust-lang.org/stable/std/cell/struct.Cell.html#impl-AsRef%3C%5BCell%3CT%3E%5D%3E-for-Cell%3C%5BT%5D%3E)
- [`bool: TryFrom<{integer}>`](https://doc.rust-lang.org/stable/std/primitive.bool.html#impl-TryFrom%3Cu128%3E-for-bool)
- [`AtomicPtr::update`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.update)
- [`AtomicPtr::try_update`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicPtr.html#method.try_update)
- [`AtomicBool::update`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicBool.html#method.update)
- [`AtomicBool::try_update`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicBool.html#method.try_update)
- [`AtomicIn::update`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicIsize.html#method.update)
- [`AtomicIn::try_update`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicIsize.html#method.try_update)
- [`AtomicUn::update`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicUsize.html#method.update)
- [`AtomicUn::try_update`](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicUsize.html#method.try_update)
- [`cfg_select!`](https://doc.rust-lang.org/stable/std/macro.cfg_select.html)
- [`mod core::range`](https://doc.rust-lang.org/stable/core/range/index.html)
- [`core::range::RangeInclusive`](https://doc.rust-lang.org/stable/core/range/struct.RangeInclusive.html)
- [`core::range::RangeInclusiveIter`](https://doc.rust-lang.org/stable/core/range/struct.RangeInclusiveIter.html)
- [`core::hint::cold_path`](https://doc.rust-lang.org/stable/core/hint/fn.cold_path.html)
- [`<*const T>::as_ref_unchecked`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.as_ref_unchecked)
- [`<*mut T>::as_ref_unchecked`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.as_ref_unchecked-1)
- [`<*mut T>::as_mut_unchecked`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.as_mut_unchecked)
- [`Vec::push_mut`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.push_mut)
- [`Vec::insert_mut`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.insert_mut)
- [`VecDeque::push_front_mut`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.push_front_mut)
- [`VecDeque::push_back_mut`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.push_back_mut)
- [`VecDeque::insert_mut`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.insert_mut)
- [`LinkedList::push_front_mut`](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html#method.push_front_mut)
- [`LinkedList::push_back_mut`](https://doc.rust-lang.org/stable/std/collections/struct.LinkedList.html#method.push_back_mut)
- [`Layout::dangling_ptr`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.dangling_ptr)
- [`Layout::repeat`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.repeat)
- [`Layout::repeat_packed`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.repeat_packed)
- [`Layout::extend_packed`](https://doc.rust-lang.org/stable/std/alloc/struct.Layout.html#method.extend_packed)
These previously stable APIs are now stable in const contexts:
- [`fmt::from_fn`](https://doc.rust-lang.org/stable/std/fmt/fn.from_fn.html)
- [`ControlFlow::is_break`](https://doc.rust-lang.org/stable/core/ops/enum.ControlFlow.html#method.is_break)
- [`ControlFlow::is_continue`](https://doc.rust-lang.org/stable/core/ops/enum.ControlFlow.html#method.is_continue)
<a id="1.95-Rustdoc"></a>
Rustdoc
-----
- [In search results, rank unstable items lower](https://github.com/rust-lang/rust/pull/149460)
- [Add new "hide deprecated items" setting in rustdoc](https://github.com/rust-lang/rust/pull/151091)
<a id="1.95-Compatibility-Notes"></a>
Compatibility Notes
-------------------
- [Array coercions may now result in less inference constraints than before](https://github.com/rust-lang/rust/pull/140283)
- Importing `$crate` without renaming, i.e. `use $crate::{self};`, is now no longer permitted due to stricter error checking for `self` imports.
- [const-eval: be more consistent in the behavior of padding during typed copies.](https://github.com/rust-lang/rust/pull/148967)
In very rare cases, this may cause compilation errors due to bytes from parts of a pointer ending up in the padding bytes of a `const` or `static`.
- [A future-incompatibility warning lint `ambiguous_glob_imported_traits` is now reported when using an ambiguously glob imported trait](https://github.com/rust-lang/rust/pull/149058)
- [Check lifetime bounds of types mentioning only type parameters](https://github.com/rust-lang/rust/pull/149389)
- [Report more visibility-related ambiguous import errors](https://github.com/rust-lang/rust/pull/149596)
- [Deprecate `Eq::assert_receiver_is_total_eq` and emit future compatibility warnings on manual impls](https://github.com/rust-lang/rust/pull/149978)
- [powerpc64: Use the ELF ABI version set in target spec instead of guessing](https://github.com/rust-lang/rust/pull/150468) (fixes the ELF ABI used by the OpenBSD target)
- Matching on a `#[non_exhaustive]` enum [now reads the discriminant, even if the enum has only one variant](https://github.com/rust-lang/rust/pull/150681). This can cause closures to capture values that they previously wouldn't.
- `mut ref` and `mut ref mut` patterns, part of the unstable [Match Ergonomics 2024 RFC](https://github.com/rust-lang/rust/issues/123076), were accidentally allowed on stable within struct pattern field shorthand. These patterns are now correctly feature-gated as unstable in this position.
- [Add future-compatibility warning for derive helper attributes which conflict with built-in attributes](https://github.com/rust-lang/rust/pull/151152)
- [JSON target specs](https://doc.rust-lang.org/rustc/targets/custom.html) have been destabilized and now require `-Z unstable-options` to use. Previously, they could not be used without the standard library, which has no stable build mechanism. In preparation for the `build-std` project adding that support, JSON target specs are being proactively gated to ensure they remain unstable even if `build-std` is stabilized. Cargo now includes the `-Z json-target-spec` CLI flag to automatically pass `-Z unstable-options` to the compiler when needed. See [#150151](https://github.com/rust-lang/rust/pull/150151), [#151534](https://github.com/rust-lang/rust/pull/150151), and [rust-lang/cargo#16557](https://github.com/rust-lang/cargo/pull/16557).
- [The arguments of `#[feature]` attributes on invalid targets are now checked](https://github.com/rust-lang/rust/issues/153764)
<a id="1.95-Internal-Changes"></a>
Internal Changes
----------------
These changes do not affect any public interfaces of Rust, but they represent
significant improvements to the performance or internals of rustc and related
tools.
- [Update to LLVM 22](https://github.com/rust-lang/rust/pull/150722)
Version 1.94.1 (2026-03-26)
===========================

View File

@@ -35,6 +35,7 @@ impl HomogeneousAggregate {
/// Try to combine two `HomogeneousAggregate`s, e.g. from two fields in
/// the same `struct`. Only succeeds if only one of them has any data,
/// or both units are identical.
#[cfg(feature = "nightly")]
fn merge(self, other: HomogeneousAggregate) -> Result<HomogeneousAggregate, Heterogeneous> {
match (self, other) {
(x, HomogeneousAggregate::NoData) | (HomogeneousAggregate::NoData, x) => Ok(x),
@@ -75,10 +76,11 @@ impl<'a, Ty> TyAndLayout<'a, Ty> {
Ok(HomogeneousAggregate::Homogeneous(Reg { kind, size: self.size }))
}
BackendRepr::SimdVector { .. } => {
BackendRepr::SimdVector { element, count: _ } => {
assert!(!self.is_zst());
Ok(HomogeneousAggregate::Homogeneous(Reg {
kind: RegKind::Vector,
kind: RegKind::Vector { hint_vector_elem: element.primitive() },
size: self.size,
}))
}

View File

@@ -1,14 +1,19 @@
#[cfg(feature = "nightly")]
use rustc_macros::HashStable_Generic;
use crate::{Align, HasDataLayout, Size};
use crate::{Align, HasDataLayout, Integer, Primitive, Size};
#[cfg_attr(feature = "nightly", derive(HashStable_Generic))]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum RegKind {
Integer,
Float,
Vector,
Vector {
/// The `hint_vector_elem` is strictly for optimization purposes. E.g. it can be used by
/// a codegen backend to prevent extra bitcasts that obscure a pattern. Alternatively,
/// it can be safely ignored by always picking i8.
hint_vector_elem: Primitive,
},
}
#[cfg_attr(feature = "nightly", derive(HashStable_Generic))]
@@ -36,6 +41,12 @@ impl Reg {
reg_ctor!(f32, Float, 32);
reg_ctor!(f64, Float, 64);
reg_ctor!(f128, Float, 128);
/// A vector of the given size with an unknown (and irrelevant) element type.
pub fn opaque_vector(size: Size) -> Reg {
// Default to an i8 vector of the given size.
Reg { kind: RegKind::Vector { hint_vector_elem: Primitive::Int(Integer::I8, true) }, size }
}
}
impl Reg {
@@ -58,7 +69,7 @@ impl Reg {
128 => dl.f128_align,
_ => panic!("unsupported float: {self:?}"),
},
RegKind::Vector => dl.llvmlike_vector_align(self.size),
RegKind::Vector { .. } => dl.llvmlike_vector_align(self.size),
}
}
}

View File

@@ -131,6 +131,29 @@ macro_rules! abi_impls {
$($e_name::$variant $( { unwind: $uw } )* => $tok,)*
}
}
// FIXME(FnSigKind): when PartialEq is stably const, use it instead
const fn internal_const_eq(&self, other: &Self) -> bool {
match (self, other) {
$( ( $e_name::$variant $( { unwind: $uw } )* , $e_name::$variant $( { unwind: $uw } )* ) => true,)*
_ => false,
}
}
// ALL_VARIANTS.iter().position(|v| v == self), but const
pub const fn as_packed(&self) -> u8 {
let mut index = 0;
while index < $e_name::ALL_VARIANTS.len() {
if self.internal_const_eq(&$e_name::ALL_VARIANTS[index]) {
return index as u8;
}
index += 1;
}
panic!("unreachable: invalid ExternAbi variant");
}
pub const fn from_packed(index: u8) -> Self {
let index = index as usize;
assert!(index < $e_name::ALL_VARIANTS.len(), "invalid ExternAbi index");
$e_name::ALL_VARIANTS[index]
}
}
impl ::core::str::FromStr for $e_name {

View File

@@ -47,11 +47,15 @@ use bitflags::bitflags;
#[cfg(feature = "nightly")]
use rustc_data_structures::stable_hasher::StableOrd;
#[cfg(feature = "nightly")]
use rustc_error_messages::{DiagArgValue, IntoDiagArg};
#[cfg(feature = "nightly")]
use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, msg};
use rustc_hashes::Hash64;
use rustc_index::{Idx, IndexSlice, IndexVec};
#[cfg(feature = "nightly")]
use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_Generic};
#[cfg(feature = "nightly")]
use rustc_span::{Symbol, sym};
mod callconv;
mod canon_abi;
@@ -770,6 +774,14 @@ impl Endian {
Self::Big => "big",
}
}
#[cfg(feature = "nightly")]
pub fn desc_symbol(&self) -> Symbol {
match self {
Self::Little => sym::little,
Self::Big => sym::big,
}
}
}
impl fmt::Debug for Endian {
@@ -1741,6 +1753,9 @@ pub struct AddressSpace(pub u32);
impl AddressSpace {
/// LLVM's `0` address space.
pub const ZERO: Self = AddressSpace(0);
/// The address space for workgroup memory on nvptx and amdgpu.
/// See e.g. the `gpu_launch_sized_workgroup_mem` intrinsic for details.
pub const GPU_WORKGROUP: Self = AddressSpace(3);
}
/// How many scalable vectors are in a `BackendRepr::ScalableVector`?
@@ -1765,6 +1780,24 @@ impl NumScalableVectors {
}
}
#[cfg(feature = "nightly")]
impl IntoDiagArg for NumScalableVectors {
fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
DiagArgValue::Str(std::borrow::Cow::Borrowed(match self.0 {
0 => panic!("`NumScalableVectors(0)` is illformed"),
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
_ => panic!("`NumScalableVectors(N)` for N>8 is illformed"),
}))
}
}
/// The way we represent values to the backend
///
/// Previously this was conflated with the "ABI" a type is given, as in the platform-specific ABI.
@@ -2021,8 +2054,7 @@ impl Niche {
assert!(size.bits() <= 128);
let max_value = size.unsigned_int_max();
let niche = v.end.wrapping_add(1)..v.start;
let available = niche.end.wrapping_sub(niche.start) & max_value;
let available = v.start.wrapping_sub(v.end).wrapping_sub(1) & max_value;
if count > available {
return None;
}
@@ -2050,7 +2082,17 @@ impl Niche {
Some((start, Scalar::Initialized { value, valid_range: v.with_end(end) }))
};
let distance_end_zero = max_value - v.end;
if v.start > v.end {
// FIXME: this ought to work for `bool` too, but that seems to be hitting a miscompilation
// <https://github.com/rust-lang/rust/pull/155473#issuecomment-4302036343>
if count == 1 && v != (WrappingRange { start: 0, end: 1 }) {
// We only need one, so just pick the one closest to zero.
// Not only does that obviously use zero if it's possible, but it also
// simplifies testing things like `Option<char>`, since looking for `-1`
// is easier than looking for `1114112` (and matches clang's `WEOF`).
let next_up = size.sign_extend(v.end.wrapping_add(1)).unsigned_abs();
let next_down = size.sign_extend(v.start.wrapping_sub(1)).unsigned_abs();
if next_down <= next_up { move_start(v) } else { move_end(v) }
} else if v.start > v.end {
// zero is unavailable because wrapping occurs
move_end(v)
} else if v.start <= distance_end_zero {

View File

@@ -140,25 +140,19 @@ impl<T> TypedArena<T> {
/// Allocates an object in the `TypedArena`, returning a reference to it.
#[inline]
pub fn alloc(&self, object: T) -> &mut T {
assert!(size_of::<T>() != 0);
if self.ptr == self.end {
self.grow(1)
}
unsafe {
if size_of::<T>() == 0 {
self.ptr.set(self.ptr.get().wrapping_byte_add(1));
let ptr = ptr::NonNull::<T>::dangling().as_ptr();
// Don't drop the object. This `write` is equivalent to `forget`.
ptr::write(ptr, object);
&mut *ptr
} else {
let ptr = self.ptr.get();
// Advance the pointer.
self.ptr.set(self.ptr.get().add(1));
// Write into uninitialized memory.
ptr::write(ptr, object);
&mut *ptr
}
let ptr = self.ptr.get();
// Advance the pointer.
self.ptr.set(self.ptr.get().add(1));
// Write into uninitialized memory.
ptr::write(ptr, object);
&mut *ptr
}
}
@@ -287,10 +281,9 @@ impl<T> TypedArena<T> {
// Also ensure that this chunk can fit `additional`.
new_cap = cmp::max(additional, new_cap);
let mut chunk = ArenaChunk::<T>::new(new_cap);
let chunk = chunks.push_mut(ArenaChunk::<T>::new(new_cap));
self.ptr.set(chunk.start());
self.end.set(chunk.end());
chunks.push(chunk);
}
}
@@ -303,16 +296,10 @@ impl<T> TypedArena<T> {
let end = self.ptr.get().addr();
// We then calculate the number of elements to be dropped in the last chunk,
// which is the filled area's length.
let diff = if size_of::<T>() == 0 {
// `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
// the number of zero-sized values in the last and only chunk, just out of caution.
// Recall that `end` was incremented for each allocated value.
end - start
} else {
// FIXME: this should *likely* use `offset_from`, but more
// investigation is needed (including running tests in miri).
(end - start) / size_of::<T>()
};
assert_ne!(size_of::<T>(), 0);
// FIXME: this should *likely* use `offset_from`, but more
// investigation is needed (including running tests in miri).
let diff = (end - start) / size_of::<T>();
// Pass that to the `destroy` method.
unsafe {
last_chunk.destroy(diff);
@@ -419,7 +406,7 @@ impl DroplessArena {
// Also ensure that this chunk can fit `additional`.
new_cap = cmp::max(additional, new_cap);
let mut chunk = ArenaChunk::new(align_up(new_cap, PAGE));
let chunk = chunks.push_mut(ArenaChunk::new(align_up(new_cap, PAGE)));
self.start.set(chunk.start());
// Align the end to DROPLESS_ALIGNMENT.
@@ -430,8 +417,6 @@ impl DroplessArena {
debug_assert!(chunk.start().addr() <= end);
self.end.set(chunk.end().with_addr(end));
chunks.push(chunk);
}
}

View File

@@ -22,7 +22,6 @@ impl<T> TypedArena<T> {
if let Some(last_chunk) = chunks_borrow.last_mut() {
self.clear_last_chunk(last_chunk);
let len = chunks_borrow.len();
// If `T` is ZST, code below has no effect.
for mut chunk in chunks_borrow.drain(..len - 1) {
chunk.destroy(chunk.entries);
}
@@ -117,18 +116,6 @@ fn test_noncopy() {
}
}
#[test]
fn test_typed_arena_zero_sized() {
let arena = TypedArena::default();
#[cfg(not(miri))]
const N: usize = 100000;
#[cfg(miri)]
const N: usize = 1000;
for _ in 0..N {
arena.alloc(());
}
}
#[test]
fn test_typed_arena_clear() {
let mut arena = TypedArena::default();
@@ -207,7 +194,8 @@ thread_local! {
static DROP_COUNTER: Cell<u32> = Cell::new(0)
}
struct SmallDroppable;
#[allow(unused)]
struct SmallDroppable(u8);
impl Drop for SmallDroppable {
fn drop(&mut self) {
@@ -222,7 +210,7 @@ fn test_typed_arena_drop_small_count() {
let arena: TypedArena<SmallDroppable> = TypedArena::default();
for _ in 0..100 {
// Allocate something with drop glue to make sure it doesn't leak.
arena.alloc(SmallDroppable);
arena.alloc(SmallDroppable(0));
}
// dropping
};

View File

@@ -15,6 +15,6 @@ rustc_macros = { path = "../rustc_macros" }
rustc_serialize = { path = "../rustc_serialize" }
rustc_span = { path = "../rustc_span" }
smallvec = { version = "1.8.1", features = ["union", "may_dangle"] }
thin-vec = "0.2.12"
thin-vec = "0.2.15"
tracing = "0.1"
# tidy-alphabetical-end

View File

@@ -3786,10 +3786,10 @@ pub struct TraitAlias {
#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub struct Trait {
pub impl_restriction: ImplRestriction,
pub constness: Const,
pub safety: Safety,
pub is_auto: IsAuto,
pub impl_restriction: ImplRestriction,
pub ident: Ident,
pub generics: Generics,
#[visitable(extra = BoundKind::SuperTraits)]
@@ -3901,12 +3901,17 @@ pub struct Delegation {
pub from_glob: bool,
}
#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub enum DelegationSuffixes {
List(ThinVec<(Ident, Option<Ident>)>),
Glob(Span),
}
#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub struct DelegationMac {
pub qself: Option<Box<QSelf>>,
pub prefix: Path,
// Some for list delegation, and None for glob delegation.
pub suffixes: Option<ThinVec<(Ident, Option<Ident>)>>,
pub suffixes: DelegationSuffixes,
pub body: Option<Box<Block>>,
}
@@ -3918,6 +3923,13 @@ pub struct StaticItem {
pub mutability: Mutability,
pub expr: Option<Box<Expr>>,
pub define_opaque: Option<ThinVec<(NodeId, Path)>>,
/// This static is an implementation of an externally implementable item (EII).
/// This means, there was an EII declared somewhere and this static is the
/// implementation that should be used for the declaration.
///
/// For statics, there may be at most one `EiiImpl`, but this is a `ThinVec` to make usages of this field nicer.
pub eii_impls: ThinVec<EiiImpl>,
}
#[derive(Clone, Encodable, Decodable, Debug, Walkable)]

View File

@@ -235,34 +235,6 @@ impl AttributeExt for Attribute {
}
}
fn deprecation_note(&self) -> Option<Ident> {
match &self.kind {
AttrKind::Normal(normal) if normal.item.path == sym::deprecated => {
let meta = &normal.item;
// #[deprecated = "..."]
if let Some(s) = meta.value_str() {
return Some(Ident { name: s, span: meta.span() });
}
// #[deprecated(note = "...")]
if let Some(list) = meta.meta_item_list() {
for nested in list {
if let Some(mi) = nested.meta_item()
&& mi.path == sym::note
&& let Some(s) = mi.value_str()
{
return Some(Ident { name: s, span: mi.span });
}
}
}
None
}
_ => None,
}
}
fn doc_resolution_scope(&self) -> Option<AttrStyle> {
match &self.kind {
AttrKind::DocComment(..) => Some(self.style),
@@ -341,6 +313,34 @@ impl Attribute {
)],
}
}
pub fn deprecation_note(&self) -> Option<Ident> {
match &self.kind {
AttrKind::Normal(normal) if normal.item.path == sym::deprecated => {
let meta = &normal.item;
// #[deprecated = "..."]
if let Some(s) = meta.value_str() {
return Some(Ident { name: s, span: meta.span() });
}
// #[deprecated(note = "...")]
if let Some(list) = meta.meta_item_list() {
for nested in list {
if let Some(mi) = nested.meta_item()
&& mi.path == sym::note
&& let Some(s) = mi.value_str()
{
return Some(Ident { name: s, span: mi.span });
}
}
}
None
}
_ => None,
}
}
}
impl AttrItem {
@@ -824,19 +824,19 @@ pub fn mk_attr_name_value_str(
mk_attr(g, style, unsafety, path, args, span)
}
pub fn filter_by_name<A: AttributeExt>(attrs: &[A], name: Symbol) -> impl Iterator<Item = &A> {
pub fn filter_by_name(attrs: &[Attribute], name: Symbol) -> impl Iterator<Item = &Attribute> {
attrs.iter().filter(move |attr| attr.has_name(name))
}
pub fn find_by_name<A: AttributeExt>(attrs: &[A], name: Symbol) -> Option<&A> {
pub fn find_by_name(attrs: &[Attribute], name: Symbol) -> Option<&Attribute> {
filter_by_name(attrs, name).next()
}
pub fn first_attr_value_str_by_name(attrs: &[impl AttributeExt], name: Symbol) -> Option<Symbol> {
pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: Symbol) -> Option<Symbol> {
find_by_name(attrs, name).and_then(|attr| attr.value_str())
}
pub fn contains_name(attrs: &[impl AttributeExt], name: Symbol) -> bool {
pub fn contains_name(attrs: &[Attribute], name: Symbol) -> bool {
find_by_name(attrs, name).is_some()
}
@@ -911,11 +911,6 @@ pub trait AttributeExt: Debug {
/// * `#[doc(...)]` returns `None`.
fn doc_str(&self) -> Option<Symbol>;
/// Returns the deprecation note if this is deprecation attribute.
/// * `#[deprecated = "note"]` returns `Some("note")`.
/// * `#[deprecated(note = "note", ...)]` returns `Some("note")`.
fn deprecation_note(&self) -> Option<Ident>;
/// Returns whether this attribute is any of the proc macro attributes.
/// i.e. `proc_macro`, `proc_macro_attribute` or `proc_macro_derive`.
fn is_proc_macro_attr(&self) -> bool {

View File

@@ -430,6 +430,7 @@ macro_rules! common_visitor_and_walkers {
Defaultness,
Delegation,
DelegationMac,
DelegationSuffixes,
DelimArgs,
DelimSpan,
EnumDef,

View File

@@ -23,6 +23,6 @@ rustc_session = { path = "../rustc_session" }
rustc_span = { path = "../rustc_span" }
rustc_target = { path = "../rustc_target" }
smallvec = { version = "1.8.1", features = ["union", "may_dangle"] }
thin-vec = "0.2.12"
thin-vec = "0.2.15"
tracing = "0.1"
# tidy-alphabetical-end

View File

@@ -18,11 +18,9 @@ use super::errors::{
InvalidRegisterClass, RegisterClassOnlyClobber, RegisterClassOnlyClobberStable,
RegisterConflict,
};
use crate::{
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, ParamMode, ResolverAstLoweringExt,
};
use crate::{AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, ParamMode};
impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
impl<'hir> LoweringContext<'_, 'hir> {
pub(crate) fn lower_inline_asm(
&mut self,
sp: Span,
@@ -203,7 +201,6 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
},
InlineAsmOperand::Sym { sym } => {
let static_def_id = self
.resolver
.get_partial_res(sym.id)
.and_then(|res| res.full_res())
.and_then(|res| match res {

View File

@@ -4,9 +4,9 @@ use rustc_hir::Target;
use rustc_span::sym;
use smallvec::SmallVec;
use crate::{ImplTraitContext, ImplTraitPosition, LoweringContext, ResolverAstLoweringExt};
use crate::{ImplTraitContext, ImplTraitPosition, LoweringContext};
impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
impl<'hir> LoweringContext<'_, 'hir> {
pub(super) fn lower_block(
&mut self,
b: &Block,

View File

@@ -2,9 +2,9 @@ use std::sync::Arc;
use thin_vec::thin_vec;
use crate::{LoweringContext, ResolverAstLoweringExt};
use crate::LoweringContext;
impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
impl<'hir> LoweringContext<'_, 'hir> {
/// Lowered contracts are guarded with the `contract_checks` compiler flag,
/// i.e. the flag turns into a boolean guard in the lowered HIR. The reason
/// for not eliminating the contract code entirely when the `contract_checks`

View File

@@ -39,16 +39,16 @@
use std::iter;
use ast::visit::Visitor;
use hir::def::{DefKind, PartialRes, Res};
use hir::def::{DefKind, Res};
use hir::{BodyId, HirId};
use rustc_abi::ExternAbi;
use rustc_ast as ast;
use rustc_ast::*;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::ErrorGuaranteed;
use rustc_hir as hir;
use rustc_hir::attrs::{AttributeKind, InlineAttr};
use rustc_hir::def_id::DefId;
use rustc_hir::{self as hir, FnDeclFlags};
use rustc_middle::span_bug;
use rustc_middle::ty::Asyncness;
use rustc_span::symbol::kw;
@@ -105,7 +105,7 @@ static ATTRS_ADDITIONS: &[AttrAdditionInfo] = &[
},
];
impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
impl<'hir> LoweringContext<'_, 'hir> {
fn is_method(&self, def_id: DefId, span: Span) -> bool {
match self.tcx.def_kind(def_id) {
DefKind::Fn => false,
@@ -143,7 +143,8 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
let (param_count, c_variadic) = self.param_count(sig_id);
let mut generics = self.uplift_delegation_generics(delegation, sig_id, item_id);
let mut generics =
self.uplift_delegation_generics(delegation, sig_id, item_id, is_method);
let body_id = self.lower_delegation_body(
delegation,
@@ -265,13 +266,13 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
}
fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
self.resolver.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
}
// Function parameter count, including C variadic `...` if present.
fn param_count(&self, def_id: DefId) -> (usize, bool /*c_variadic*/) {
let sig = self.tcx.fn_sig(def_id).skip_binder().skip_binder();
(sig.inputs().len() + usize::from(sig.c_variadic), sig.c_variadic)
(sig.inputs().len() + usize::from(sig.c_variadic()), sig.c_variadic())
}
fn lower_delegation_decl(
@@ -301,6 +302,8 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
hir::InferDelegationSig::Output(self.arena.alloc(hir::DelegationGenerics {
child_args_segment_id: generics.child.args_segment_id,
parent_args_segment_id: generics.parent.args_segment_id,
self_ty_id: generics.self_ty_id,
propagate_self_ty: generics.propagate_self_ty,
})),
)),
span,
@@ -309,9 +312,9 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
self.arena.alloc(hir::FnDecl {
inputs,
output: hir::FnRetTy::Return(output),
c_variadic,
lifetime_elision_allowed: true,
implicit_self: hir::ImplicitSelfKind::None,
fn_decl_kind: FnDeclFlags::default()
.set_lifetime_elision_allowed(true)
.set_c_variadic(c_variadic),
})
}
@@ -331,11 +334,11 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
safety: if self.tcx.codegen_fn_attrs(sig_id).safe_target_features {
hir::HeaderSafety::SafeTargetFeatures
} else {
hir::HeaderSafety::Normal(sig.safety)
hir::HeaderSafety::Normal(sig.safety())
},
constness: self.tcx.constness(sig_id),
asyncness,
abi: sig.abi,
abi: sig.abi(),
};
hir::FnSig { decl, header, span }
@@ -414,7 +417,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
&& idx == 0
{
let mut self_resolver = SelfResolver {
resolver: this.resolver,
ctxt: this,
path_id: delegation.id,
self_param_id: pat_node_id,
};
@@ -433,7 +436,6 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
// also nested delegations may need to access information about this code (#154332),
// so it is better to leave this code as opposed to bodies of extern functions,
// which are completely erased from existence.
// FIXME(fn_delegation): fix `help` in error message (see `inner-attr.stderr`)
if param_count == 0
&& let Some(block) = block
{
@@ -506,7 +508,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
// FIXME(fn_delegation): proper support for parent generics propagation
// in method call scenario.
let segment = self.process_segment(span, &segment, &mut generics.child, false);
let segment = self.process_segment(span, &segment, &mut generics.child);
let segment = self.arena.alloc(segment);
self.arena.alloc(hir::Expr {
@@ -532,14 +534,10 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
new_path.segments = self.arena.alloc_from_iter(
new_path.segments.iter().enumerate().map(|(idx, segment)| {
let mut process_segment = |result, add_lifetimes| {
self.process_segment(span, segment, result, add_lifetimes)
};
if idx + 2 == len {
process_segment(&mut generics.parent, true)
self.process_segment(span, segment, &mut generics.parent)
} else if idx + 1 == len {
process_segment(&mut generics.child, false)
self.process_segment(span, segment, &mut generics.child)
} else {
segment.clone()
}
@@ -549,12 +547,18 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
hir::QPath::Resolved(ty, self.arena.alloc(new_path))
}
hir::QPath::TypeRelative(ty, segment) => {
let segment = self.process_segment(span, segment, &mut generics.child, false);
let segment = self.process_segment(span, segment, &mut generics.child);
hir::QPath::TypeRelative(ty, self.arena.alloc(segment))
}
};
generics.self_ty_id = match new_path {
hir::QPath::Resolved(ty, _) => ty,
hir::QPath::TypeRelative(ty, _) => Some(ty),
}
.map(|ty| ty.hir_id);
let callee_path = self.arena.alloc(self.mk_expr(hir::ExprKind::Path(new_path), span));
self.arena.alloc(self.mk_expr(hir::ExprKind::Call(callee_path, args), span))
};
@@ -576,13 +580,12 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
span: Span,
segment: &hir::PathSegment<'hir>,
result: &mut GenericsGenerationResult<'hir>,
add_lifetimes: bool,
) -> hir::PathSegment<'hir> {
let details = result.generics.args_propagation_details();
let segment = if details.should_propagate {
let generics = result.generics.into_hir_generics(self, span);
let args = generics.into_generic_args(self, add_lifetimes, span);
let args = generics.into_generic_args(self, span);
// Needed for better error messages (`trait-impl-wrong-args-count.rs` test).
let args = if args.is_empty() { None } else { Some(args) };
@@ -604,13 +607,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
span: Span,
delegation: &Delegation,
) -> DelegationResults<'hir> {
let decl = self.arena.alloc(hir::FnDecl {
inputs: &[],
output: hir::FnRetTy::DefaultReturn(span),
c_variadic: false,
lifetime_elision_allowed: true,
implicit_self: hir::ImplicitSelfKind::None,
});
let decl = self.arena.alloc(hir::FnDecl::dummy(span));
let header = self.generate_header_error();
let sig = hir::FnSig { decl, header, span };
@@ -668,25 +665,24 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
}
}
struct SelfResolver<'a, R> {
resolver: &'a mut R,
struct SelfResolver<'a, 'b, 'hir> {
ctxt: &'a mut LoweringContext<'b, 'hir>,
path_id: NodeId,
self_param_id: NodeId,
}
impl<'tcx, R: ResolverAstLoweringExt<'tcx>> SelfResolver<'_, R> {
impl SelfResolver<'_, '_, '_> {
fn try_replace_id(&mut self, id: NodeId) {
if let Some(res) = self.resolver.get_partial_res(id)
if let Some(res) = self.ctxt.get_partial_res(id)
&& let Some(Res::Local(sig_id)) = res.full_res()
&& sig_id == self.path_id
{
let new_res = PartialRes::new(Res::Local(self.self_param_id));
self.resolver.insert_partial_res(id, new_res);
self.ctxt.partial_res_overrides.insert(id, self.self_param_id);
}
}
}
impl<'ast, 'tcx, R: ResolverAstLoweringExt<'tcx>> Visitor<'ast> for SelfResolver<'_, R> {
impl<'ast> Visitor<'ast> for SelfResolver<'_, '_, '_> {
fn visit_id(&mut self, id: NodeId) {
self.try_replace_id(id);
}

View File

@@ -6,22 +6,57 @@ use rustc_hir::def_id::DefId;
use rustc_middle::ty::GenericParamDefKind;
use rustc_middle::{bug, ty};
use rustc_span::symbol::kw;
use rustc_span::{Ident, Span};
use rustc_span::{Ident, Span, sym};
use crate::{LoweringContext, ResolverAstLoweringExt};
use crate::LoweringContext;
pub(super) enum DelegationGenerics<T> {
#[derive(Clone, Copy)]
pub(super) enum DelegationGenericsKind {
/// User-specified args are present: `reuse foo::<String>;`.
UserSpecified,
/// The default case when no user-specified args are present: `reuse Trait::foo;`.
Default(T),
Default,
/// In free-to-trait reuse, when user specified args for trait `reuse Trait::<i32>::foo;`
/// in this case we need to both generate `Self` and process user args.
SelfAndUserSpecified(T),
SelfAndUserSpecified,
/// In delegations from trait impl to other entities like free functions or trait functions,
/// we want to generate a function whose generics matches generics of signature function
/// in trait.
TraitImpl(T, bool /* Has user-specified args */),
TraitImpl(bool /* Has user-specified args */),
}
#[derive(Debug, Clone, Copy)]
pub(super) enum GenericsPosition {
Parent,
Child,
}
pub(super) struct DelegationGenerics<T> {
generics: T,
kind: DelegationGenericsKind,
pos: GenericsPosition,
}
impl<'hir> DelegationGenerics<&'hir [ty::GenericParamDef]> {
fn default(generics: &'hir [ty::GenericParamDef], pos: GenericsPosition) -> Self {
DelegationGenerics { generics, pos, kind: DelegationGenericsKind::Default }
}
fn user_specified(generics: &'hir [ty::GenericParamDef], pos: GenericsPosition) -> Self {
DelegationGenerics { generics, pos, kind: DelegationGenericsKind::UserSpecified }
}
fn trait_impl(
generics: &'hir [ty::GenericParamDef],
user_specified: bool,
pos: GenericsPosition,
) -> Self {
DelegationGenerics {
generics,
pos,
kind: DelegationGenericsKind::TraitImpl(user_specified),
}
}
}
/// Used for storing either ty generics or their uplifted HIR version. First we obtain
@@ -47,6 +82,8 @@ pub(super) struct GenericsGenerationResult<'hir> {
pub(super) struct GenericsGenerationResults<'hir> {
pub(super) parent: GenericsGenerationResult<'hir>,
pub(super) child: GenericsGenerationResult<'hir>,
pub(super) self_ty_id: Option<HirId>,
pub(super) propagate_self_ty: bool,
}
pub(super) struct GenericArgsPropagationDetails {
@@ -54,20 +91,19 @@ pub(super) struct GenericArgsPropagationDetails {
pub(super) use_args_in_sig_inheritance: bool,
}
impl<T> DelegationGenerics<T> {
fn args_propagation_details(&self) -> GenericArgsPropagationDetails {
impl DelegationGenericsKind {
fn args_propagation_details(self) -> GenericArgsPropagationDetails {
match self {
DelegationGenerics::UserSpecified | DelegationGenerics::SelfAndUserSpecified { .. } => {
GenericArgsPropagationDetails {
should_propagate: false,
use_args_in_sig_inheritance: true,
}
}
DelegationGenerics::TraitImpl(_, user_specified) => GenericArgsPropagationDetails {
should_propagate: !*user_specified,
DelegationGenericsKind::UserSpecified
| DelegationGenericsKind::SelfAndUserSpecified => GenericArgsPropagationDetails {
should_propagate: false,
use_args_in_sig_inheritance: true,
},
DelegationGenericsKind::TraitImpl(user_specified) => GenericArgsPropagationDetails {
should_propagate: !user_specified,
use_args_in_sig_inheritance: false,
},
DelegationGenerics::Default(_) => GenericArgsPropagationDetails {
DelegationGenericsKind::Default => GenericArgsPropagationDetails {
should_propagate: true,
use_args_in_sig_inheritance: false,
},
@@ -78,28 +114,18 @@ impl<T> DelegationGenerics<T> {
impl<'hir> HirOrTyGenerics<'hir> {
pub(super) fn into_hir_generics(
&mut self,
ctx: &mut LoweringContext<'_, 'hir, impl ResolverAstLoweringExt<'hir>>,
ctx: &mut LoweringContext<'_, 'hir>,
span: Span,
) -> &mut HirOrTyGenerics<'hir> {
if let HirOrTyGenerics::Ty(params) = self {
let mut uplift_params = |generics: &'hir [ty::GenericParamDef]| {
ctx.uplift_delegation_generic_params(span, generics)
};
if let HirOrTyGenerics::Ty(ty) = self {
let rename_self = matches!(ty.pos, GenericsPosition::Child);
let params = ctx.uplift_delegation_generic_params(span, ty.generics, rename_self);
let hir_generics = match params {
DelegationGenerics::UserSpecified => DelegationGenerics::UserSpecified,
DelegationGenerics::Default(params) => {
DelegationGenerics::Default(uplift_params(params))
}
DelegationGenerics::SelfAndUserSpecified(params) => {
DelegationGenerics::SelfAndUserSpecified(uplift_params(params))
}
DelegationGenerics::TraitImpl(params, user_specified) => {
DelegationGenerics::TraitImpl(uplift_params(params), *user_specified)
}
};
*self = HirOrTyGenerics::Hir(hir_generics);
*self = HirOrTyGenerics::Hir(DelegationGenerics {
generics: params,
kind: ty.kind,
pos: ty.pos,
});
}
self
@@ -108,40 +134,30 @@ impl<'hir> HirOrTyGenerics<'hir> {
fn hir_generics_or_empty(&self) -> &'hir hir::Generics<'hir> {
match self {
HirOrTyGenerics::Ty(_) => hir::Generics::empty(),
HirOrTyGenerics::Hir(hir_generics) => match hir_generics {
DelegationGenerics::UserSpecified => hir::Generics::empty(),
DelegationGenerics::Default(generics)
| DelegationGenerics::SelfAndUserSpecified(generics)
| DelegationGenerics::TraitImpl(generics, _) => generics,
},
HirOrTyGenerics::Hir(hir) => hir.generics,
}
}
pub(super) fn into_generic_args(
&self,
ctx: &mut LoweringContext<'_, 'hir, impl ResolverAstLoweringExt<'hir>>,
add_lifetimes: bool,
ctx: &mut LoweringContext<'_, 'hir>,
span: Span,
) -> &'hir hir::GenericArgs<'hir> {
match self {
HirOrTyGenerics::Ty(_) => {
bug!("Attempting to get generic args before uplifting to HIR")
}
HirOrTyGenerics::Hir(hir_generics) => match hir_generics {
DelegationGenerics::UserSpecified => hir::GenericArgs::NONE,
DelegationGenerics::Default(generics)
| DelegationGenerics::SelfAndUserSpecified(generics)
| DelegationGenerics::TraitImpl(generics, _) => {
ctx.create_generics_args_from_params(generics.params, add_lifetimes, span)
}
},
HirOrTyGenerics::Hir(hir) => {
let add_lifetimes = matches!(hir.pos, GenericsPosition::Parent);
ctx.create_generics_args_from_params(hir.generics.params, add_lifetimes, span)
}
}
}
pub(super) fn args_propagation_details(&self) -> GenericArgsPropagationDetails {
match self {
HirOrTyGenerics::Ty(ty_generics) => ty_generics.args_propagation_details(),
HirOrTyGenerics::Hir(hir_generics) => hir_generics.args_propagation_details(),
HirOrTyGenerics::Ty(ty) => ty.kind.args_propagation_details(),
HirOrTyGenerics::Hir(hir) => hir.kind.args_propagation_details(),
}
}
}
@@ -158,7 +174,7 @@ impl<'hir> GenericsGenerationResults<'hir> {
pub(super) fn all_params(
&mut self,
span: Span,
ctx: &mut LoweringContext<'_, 'hir, impl ResolverAstLoweringExt<'hir>>,
ctx: &mut LoweringContext<'_, 'hir>,
) -> impl Iterator<Item = hir::GenericParam<'hir>> {
// Now we always call `into_hir_generics` both on child and parent,
// however in future we would not do that, when scenarios like
@@ -192,7 +208,7 @@ impl<'hir> GenericsGenerationResults<'hir> {
pub(super) fn all_predicates(
&mut self,
span: Span,
ctx: &mut LoweringContext<'_, 'hir, impl ResolverAstLoweringExt<'hir>>,
ctx: &mut LoweringContext<'_, 'hir>,
) -> impl Iterator<Item = hir::WherePredicate<'hir>> {
// Now we always call `into_hir_generics` both on child and parent,
// however in future we would not do that, when scenarios like
@@ -210,12 +226,13 @@ impl<'hir> GenericsGenerationResults<'hir> {
}
}
impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
impl<'hir> LoweringContext<'_, 'hir> {
pub(super) fn uplift_delegation_generics(
&mut self,
delegation: &Delegation,
sig_id: DefId,
item_id: NodeId,
is_method: bool,
) -> GenericsGenerationResults<'hir> {
let delegation_parent_kind =
self.tcx.def_kind(self.tcx.local_parent(self.local_def_id(item_id)));
@@ -231,12 +248,23 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
if matches!(delegation_parent_kind, DefKind::Impl { of_trait: true }) {
// Considering parent generics, during signature inheritance
// we will take those args that are in trait impl header trait ref.
let parent = GenericsGenerationResult::new(DelegationGenerics::TraitImpl(&[], true));
let parent = DelegationGenerics::trait_impl(&[], true, GenericsPosition::Parent);
let parent = GenericsGenerationResult::new(parent);
let child = DelegationGenerics::trait_impl(
sig_params,
child_user_specified,
GenericsPosition::Child,
);
let child = DelegationGenerics::TraitImpl(sig_params, child_user_specified);
let child = GenericsGenerationResult::new(child);
return GenericsGenerationResults { parent, child };
return GenericsGenerationResults {
parent,
child,
self_ty_id: None,
propagate_self_ty: false,
};
}
let delegation_in_free_ctx =
@@ -244,40 +272,56 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
let sig_parent = self.tcx.parent(sig_id);
let sig_in_trait = matches!(self.tcx.def_kind(sig_parent), DefKind::Trait);
let free_to_trait_delegation = delegation_in_free_ctx && sig_in_trait;
let generate_self = free_to_trait_delegation && is_method && delegation.qself.is_none();
let can_add_generics_to_parent = len >= 2
&& self.get_resolution_id(segments[len - 2].id).is_some_and(|def_id| {
matches!(self.tcx.def_kind(def_id), DefKind::Trait | DefKind::TraitAlias)
});
let generate_self = delegation_in_free_ctx && sig_in_trait;
let parent_generics = if can_add_generics_to_parent {
let sig_parent_params = &self.tcx.generics_of(sig_parent).own_params[..];
if segments[len - 2].args.is_some() {
if generate_self {
// Take only first Self parameter, it is trait so Self must be present.
DelegationGenerics::SelfAndUserSpecified(&sig_parent_params[..1])
DelegationGenerics {
kind: DelegationGenericsKind::SelfAndUserSpecified,
generics: &sig_parent_params[..1],
pos: GenericsPosition::Parent,
}
} else {
DelegationGenerics::UserSpecified
DelegationGenerics::user_specified(&[], GenericsPosition::Parent)
}
} else {
let skip_self = usize::from(!generate_self);
DelegationGenerics::Default(&sig_parent_params[skip_self..])
DelegationGenerics::default(
&sig_parent_params[skip_self..],
GenericsPosition::Parent,
)
}
} else {
DelegationGenerics::<&'hir [ty::GenericParamDef]>::Default(&[])
DelegationGenerics::default(&[], GenericsPosition::Parent)
};
let child_generics = if child_user_specified {
DelegationGenerics::UserSpecified
let synth_params_index =
sig_params.iter().position(|p| p.kind.is_synthetic()).unwrap_or(sig_params.len());
DelegationGenerics::user_specified(
&sig_params[synth_params_index..],
GenericsPosition::Child,
)
} else {
DelegationGenerics::Default(sig_params)
DelegationGenerics::default(sig_params, GenericsPosition::Child)
};
GenericsGenerationResults {
parent: GenericsGenerationResult::new(parent_generics),
child: GenericsGenerationResult::new(child_generics),
self_ty_id: None,
propagate_self_ty: free_to_trait_delegation && !generate_self,
}
}
@@ -285,6 +329,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
&mut self,
span: Span,
params: &'hir [ty::GenericParamDef],
rename_self: bool,
) -> &'hir hir::Generics<'hir> {
let params = self.arena.alloc_from_iter(params.iter().map(|p| {
let def_kind = match p.kind {
@@ -293,12 +338,24 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
GenericParamDefKind::Const { .. } => DefKind::ConstParam,
};
let param_ident = Ident::new(p.name, span);
// Rename Self generic param to This so it is properly propagated.
// If the user will create a function `fn foo<Self>() {}` with generic
// param "Self" then it will not be generated in HIR, the same thing
// applies to traits, `trait Trait<Self> {}` will be represented as
// `trait Trait {}` in HIR and "unexpected keyword `Self` in generic parameters"
// error will be emitted.
// Note that we do not rename `Self` to `This` after non-recursive reuse
// from Trait, in this case the `Self` should not be propagated
// (we rely that implicit `Self` generic param of a trait is named "Self")
// and it is OK to have Self generic param generated during lowering.
let param_name =
if rename_self && p.name == kw::SelfUpper { sym::This } else { p.name };
let param_ident = Ident::new(param_name, span);
let def_name = Some(param_ident.name);
let path_data = def_kind.def_path_data(def_name);
let node_id = self.next_node_id();
let def_id = self.create_def(node_id, def_name, def_kind, path_data, span);
let def_id = self.create_def(node_id, def_name, def_kind, span);
let kind = match p.kind {
GenericParamDefKind::Lifetime => {

View File

@@ -8,7 +8,6 @@ use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_errors::msg;
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::definitions::DefPathData;
use rustc_hir::{HirId, Target, find_attr};
use rustc_middle::span_bug;
use rustc_middle::ty::TyCtxt;
@@ -29,7 +28,7 @@ use super::{
use crate::errors::{InvalidLegacyConstGenericArg, UseConstGenericArg, YieldInClosure};
use crate::{AllowReturnTypeNotation, FnDeclKind, ImplTraitPosition, TryBlockScope};
struct WillCreateDefIdsVisitor {}
pub(super) struct WillCreateDefIdsVisitor;
impl<'v> rustc_ast::visit::Visitor<'v> for WillCreateDefIdsVisitor {
type Result = ControlFlow<Span>;
@@ -52,7 +51,7 @@ impl<'v> rustc_ast::visit::Visitor<'v> for WillCreateDefIdsVisitor {
}
}
impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
impl<'hir> LoweringContext<'_, 'hir> {
fn lower_exprs(&mut self, exprs: &[Box<Expr>]) -> &'hir [hir::Expr<'hir>] {
self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
}
@@ -472,25 +471,19 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
for (idx, arg) in args.iter().cloned().enumerate() {
if legacy_args_idx.contains(&idx) {
let node_id = self.next_node_id();
self.create_def(
node_id,
None,
DefKind::AnonConst,
DefPathData::LateAnonConst,
f.span,
);
let mut visitor = WillCreateDefIdsVisitor {};
let const_value = if let ControlFlow::Break(span) = visitor.visit_expr(&arg) {
Box::new(Expr {
id: self.next_node_id(),
kind: ExprKind::Err(invalid_expr_error(self.tcx, span)),
span: f.span,
attrs: [].into(),
tokens: None,
})
} else {
arg
};
self.create_def(node_id, None, DefKind::AnonConst, f.span);
let const_value =
if let ControlFlow::Break(span) = WillCreateDefIdsVisitor.visit_expr(&arg) {
Box::new(Expr {
id: self.next_node_id(),
kind: ExprKind::Err(invalid_expr_error(self.tcx, span)),
span: f.span,
attrs: [].into(),
tokens: None,
})
} else {
arg
};
let anon_const = AnonConst {
id: node_id,
@@ -762,9 +755,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
let fn_decl = self.arena.alloc(hir::FnDecl {
inputs,
output,
c_variadic: false,
implicit_self: hir::ImplicitSelfKind::None,
lifetime_elision_allowed: false,
fn_decl_kind: hir::FnDeclFlags::default(),
});
let body = self.lower_body(move |this| {
@@ -1244,10 +1235,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
whole_span: Span,
) -> hir::ExprKind<'hir> {
// Return early in case of an ordinary assignment.
fn is_ordinary<'hir>(
lower_ctx: &mut LoweringContext<'_, 'hir, impl ResolverAstLoweringExt<'hir>>,
lhs: &Expr,
) -> bool {
fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
match &lhs.kind {
ExprKind::Array(..)
| ExprKind::Struct(..)
@@ -1302,7 +1290,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
) -> Option<(&'a Option<Box<QSelf>>, &'a Path)> {
if let ExprKind::Path(qself, path) = &expr.kind {
// Does the path resolve to something disallowed in a tuple struct/variant pattern?
if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
if let Some(partial_res) = self.get_partial_res(expr.id) {
if let Some(res) = partial_res.full_res()
&& !res.expected_in_tuple_struct_pat()
{
@@ -1324,7 +1312,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
) -> Option<(&'a Option<Box<QSelf>>, &'a Path)> {
if let ExprKind::Path(qself, path) = &expr.kind {
// Does the path resolve to something disallowed in a unit struct/variant pattern?
if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
if let Some(partial_res) = self.get_partial_res(expr.id) {
if let Some(res) = partial_res.full_res()
&& !res.expected_in_unit_struct_pat()
{

View File

@@ -7,9 +7,8 @@ use rustc_session::config::FmtDebug;
use rustc_span::{ByteSymbol, DesugaringKind, Ident, Span, Symbol, sym};
use super::LoweringContext;
use crate::ResolverAstLoweringExt;
impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
impl<'hir> LoweringContext<'_, 'hir> {
pub(crate) fn lower_format_args(&mut self, sp: Span, fmt: &FormatArgs) -> hir::ExprKind<'hir> {
// Never call the const constructor of `fmt::Arguments` if the
// format_args!() had any arguments _before_ flattening/inlining.
@@ -231,7 +230,7 @@ enum ArgumentType {
/// <core::fmt::Argument>::new_…(arg)
/// ```
fn make_argument<'hir>(
ctx: &mut LoweringContext<'_, 'hir, impl ResolverAstLoweringExt<'hir>>,
ctx: &mut LoweringContext<'_, 'hir>,
sp: Span,
arg: &'hir hir::Expr<'hir>,
ty: ArgumentType,
@@ -278,7 +277,7 @@ fn make_count(
}
fn expand_format_args<'hir>(
ctx: &mut LoweringContext<'_, 'hir, impl ResolverAstLoweringExt<'hir>>,
ctx: &mut LoweringContext<'_, 'hir>,
macsp: Span,
fmt: &FormatArgs,
allow_const: bool,

View File

@@ -13,7 +13,7 @@ use rustc_hir::{
};
use rustc_index::{IndexSlice, IndexVec};
use rustc_middle::span_bug;
use rustc_middle::ty::TyCtxt;
use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
use rustc_span::def_id::DefId;
use rustc_span::edit_distance::find_best_match_for_name;
use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
@@ -24,8 +24,8 @@ use tracing::instrument;
use super::errors::{InvalidAbi, InvalidAbiSuggestion, TupleStructWithDefault, UnionWithDefault};
use super::stability::{enabled_names, gate_unstable_abi};
use super::{
AstOwner, FnDeclKind, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
RelaxedBoundForbiddenReason, RelaxedBoundPolicy, ResolverAstLoweringExt,
AstOwner, FnDeclKind, GenericArgsMode, ImplTraitContext, ImplTraitPosition, LoweringContext,
ParamMode, RelaxedBoundForbiddenReason, RelaxedBoundPolicy, ResolverAstLoweringExt,
};
/// Wraps either IndexVec (during `hir_crate`), which acts like a primary
@@ -38,7 +38,7 @@ pub(super) enum Owners<'a, 'hir> {
}
impl<'hir> Owners<'_, 'hir> {
pub(super) fn get_or_insert_mut(&mut self, def_id: LocalDefId) -> &mut hir::MaybeOwner<'hir> {
fn get_or_insert_mut(&mut self, def_id: LocalDefId) -> &mut hir::MaybeOwner<'hir> {
match self {
Owners::IndexVec(index_vec) => {
index_vec.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom)
@@ -48,9 +48,9 @@ impl<'hir> Owners<'_, 'hir> {
}
}
pub(super) struct ItemLowerer<'a, 'hir, R> {
pub(super) struct ItemLowerer<'a, 'hir> {
pub(super) tcx: TyCtxt<'hir>,
pub(super) resolver: &'a mut R,
pub(super) resolver: &'a ResolverAstLowering<'hir>,
pub(super) ast_index: &'a IndexSlice<LocalDefId, AstOwner<'a>>,
pub(super) owners: Owners<'a, 'hir>,
}
@@ -74,11 +74,11 @@ fn add_ty_alias_where_clause(
if before.0 || !after.0 { before } else { after };
}
impl<'hir, R: ResolverAstLoweringExt<'hir>> ItemLowerer<'_, 'hir, R> {
impl<'hir> ItemLowerer<'_, 'hir> {
fn with_lctx(
&mut self,
owner: NodeId,
f: impl FnOnce(&mut LoweringContext<'_, 'hir, R>) -> hir::OwnerNode<'hir>,
f: impl for<'a> FnOnce(&mut LoweringContext<'a, 'hir>) -> hir::OwnerNode<'hir>,
) {
let mut lctx = LoweringContext::new(self.tcx, self.resolver);
lctx.with_hir_id_owner(owner, |lctx| f(lctx));
@@ -122,7 +122,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> ItemLowerer<'_, 'hir, R> {
}
}
impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
impl<'hir> LoweringContext<'_, 'hir> {
pub(super) fn lower_mod(
&mut self,
items: &[Box<Item>],
@@ -213,8 +213,14 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
i: &ItemKind,
) -> Vec<hir::Attribute> {
match i {
ItemKind::Fn(box Fn { eii_impls, .. }) if eii_impls.is_empty() => Vec::new(),
ItemKind::Fn(box Fn { eii_impls, .. }) => {
ItemKind::Fn(box Fn { eii_impls, .. })
| ItemKind::Static(box StaticItem { eii_impls, .. })
if eii_impls.is_empty() =>
{
Vec::new()
}
ItemKind::Fn(box Fn { eii_impls, .. })
| ItemKind::Static(box StaticItem { eii_impls, .. }) => {
vec![hir::Attribute::Parsed(AttributeKind::EiiImpls(
eii_impls.iter().map(|i| self.lower_eii_impl(i)).collect(),
))]
@@ -226,7 +232,6 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
ItemKind::ExternCrate(..)
| ItemKind::Use(..)
| ItemKind::Static(..)
| ItemKind::Const(..)
| ItemKind::ConstBlock(..)
| ItemKind::Mod(..)
@@ -302,6 +307,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
mutability: m,
expr: e,
define_opaque,
eii_impls: _,
}) => {
let ident = self.lower_ident(*ident);
let ty = self
@@ -537,17 +543,17 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
})
}
ItemKind::Trait(box Trait {
impl_restriction,
constness,
is_auto,
safety,
// FIXME(impl_restrictions): lower to HIR
impl_restriction: _,
ident,
generics,
bounds,
items,
}) => {
let constness = self.lower_constness(*constness);
let impl_restriction = self.lower_impl_restriction(impl_restriction);
let ident = self.lower_ident(*ident);
let (generics, (safety, items, bounds)) = self.lower_generics(
generics,
@@ -566,7 +572,16 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
(safety, items, bounds)
},
);
hir::ItemKind::Trait(constness, *is_auto, safety, ident, generics, bounds, items)
hir::ItemKind::Trait(
impl_restriction,
constness,
*is_auto,
safety,
ident,
generics,
bounds,
items,
)
}
ItemKind::TraitAlias(box TraitAlias { constness, ident, generics, bounds }) => {
let constness = self.lower_constness(*constness);
@@ -620,7 +635,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
}
fn lower_path_simple_eii(&mut self, id: NodeId, path: &Path) -> Option<DefId> {
let res = self.resolver.get_partial_res(id)?;
let res = self.get_partial_res(id)?;
let Some(did) = res.expect_full_res().opt_def_id() else {
self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
return None;
@@ -817,6 +832,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
expr: _,
safety,
define_opaque,
eii_impls: _,
}) => {
let ty = self
.lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
@@ -1320,7 +1336,6 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
ImplItemImplKind::Trait {
defaultness,
trait_item_def_id: self
.resolver
.get_partial_res(i.id)
.and_then(|r| r.expect_full_res().opt_def_id())
.ok_or_else(|| {
@@ -1516,7 +1531,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
pub(crate) fn lower_coroutine_body_with_moved_arguments(
&mut self,
decl: &FnDecl,
lower_body: impl FnOnce(&mut LoweringContext<'_, 'hir, R>) -> hir::Expr<'hir>,
lower_body: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::Expr<'hir>,
fn_decl_span: Span,
body_span: Span,
coroutine_kind: CoroutineKind,
@@ -1653,7 +1668,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
parameters.push(new_parameter);
}
let mkbody = |this: &mut LoweringContext<'_, 'hir, R>| {
let mkbody = |this: &mut LoweringContext<'_, 'hir>| {
// Create a block from the user's function body:
let user_body = lower_body(this);
@@ -1831,6 +1846,38 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
}
}
pub(super) fn lower_impl_restriction(
&mut self,
r: &ImplRestriction,
) -> &'hir hir::ImplRestriction<'hir> {
let kind = match &r.kind {
RestrictionKind::Unrestricted => hir::RestrictionKind::Unrestricted,
RestrictionKind::Restricted { path, id, shorthand: _ } => {
let res = self.get_partial_res(*id);
if let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) {
hir::RestrictionKind::Restricted(self.arena.alloc(hir::Path {
res: did,
segments: self.arena.alloc_from_iter(path.segments.iter().map(|segment| {
self.lower_path_segment(
path.span,
segment,
ParamMode::Explicit,
GenericArgsMode::Err,
ImplTraitContext::Disallowed(ImplTraitPosition::Path),
None,
)
})),
span: self.lower_span(path.span),
}))
} else {
self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
hir::RestrictionKind::Unrestricted
}
}
};
self.arena.alloc(hir::ImplRestriction { kind, span: self.lower_span(r.span) })
}
/// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
/// the carried impl trait definitions and bounds.
#[instrument(level = "debug", skip(self, f))]
@@ -1872,7 +1919,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
// Introduce extra lifetimes if late resolution tells us to.
let extra_lifetimes = self.resolver.extra_lifetime_params(parent_node_id);
params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
params.extend(extra_lifetimes.into_iter().filter_map(|&(ident, node_id, res)| {
self.lifetime_res_to_generic_param(
ident,
node_id,
@@ -1914,7 +1961,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
return;
};
let define_opaque = define_opaque.iter().filter_map(|(id, path)| {
let res = self.resolver.get_partial_res(*id);
let res = self.get_partial_res(*id);
let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) else {
self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
return None;

View File

@@ -39,9 +39,9 @@ use std::mem;
use std::sync::Arc;
use rustc_ast::node_id::NodeMap;
use rustc_ast::visit::AssocCtxt;
use rustc_ast::visit::Visitor;
use rustc_ast::{self as ast, *};
use rustc_attr_parsing::{AttributeParser, Late, OmitDoc};
use rustc_attr_parsing::{AttributeParser, EmitAttribute, Late, OmitDoc};
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::fx::FxIndexSet;
use rustc_data_structures::sorted_map::SortedMap;
@@ -51,8 +51,8 @@ use rustc_data_structures::tagged_ptr::TaggedRef;
use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle};
use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId};
use rustc_hir::definitions::{DefPathData, DisambiguatorState};
use rustc_hir::lints::{AttributeLint, DelayedLint};
use rustc_hir::definitions::PerParentDisambiguatorState;
use rustc_hir::lints::{AttributeLint, DelayedLint, DynAttribute};
use rustc_hir::{
self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LifetimeSource,
LifetimeSyntax, ParamName, Target, TraitCandidate, find_attr,
@@ -91,10 +91,10 @@ mod pat;
mod path;
pub mod stability;
struct LoweringContext<'a, 'hir, R> {
struct LoweringContext<'a, 'hir> {
tcx: TyCtxt<'hir>,
resolver: &'a mut R,
disambiguator: DisambiguatorState,
resolver: &'a ResolverAstLowering<'hir>,
current_disambiguator: PerParentDisambiguatorState,
/// Used to allocate HIR nodes.
arena: &'hir hir::Arena<'hir>,
@@ -138,6 +138,16 @@ struct LoweringContext<'a, 'hir, R> {
/// NodeIds that are lowered inside the current HIR owner. Only used for duplicate lowering check.
#[cfg(debug_assertions)]
node_id_to_local_id: NodeMap<hir::ItemLocalId>,
/// The `NodeId` space is split in two.
/// `0..resolver.next_node_id` are created by the resolver on the AST.
/// The higher part `resolver.next_node_id..next_node_id` are created during lowering.
next_node_id: NodeId,
/// Maps the `NodeId`s created during lowering to `LocalDefId`s.
node_id_to_def_id: NodeMap<LocalDefId>,
/// Overlay over resolver's `partial_res_map` used by delegation.
/// This only contains `PartialRes::new(Res::Local(self_param_id))`,
/// so we only store `self_param_id`.
partial_res_overrides: NodeMap<NodeId>,
allow_contracts: Arc<[Symbol]>,
allow_try_trait: Arc<[Symbol]>,
@@ -153,13 +163,13 @@ struct LoweringContext<'a, 'hir, R> {
attribute_parser: AttributeParser<'hir>,
}
impl<'a, 'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'a, 'hir, R> {
fn new(tcx: TyCtxt<'hir>, resolver: &'a mut R) -> Self {
impl<'a, 'hir> LoweringContext<'a, 'hir> {
fn new(tcx: TyCtxt<'hir>, resolver: &'a ResolverAstLowering<'hir>) -> Self {
let registered_tools = tcx.registered_tools(()).iter().map(|x| x.name).collect();
Self {
tcx,
resolver,
disambiguator: DisambiguatorState::new(),
current_disambiguator: Default::default(),
arena: tcx.hir_arena,
// HirId handling.
@@ -174,6 +184,9 @@ impl<'a, 'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'a, 'hir, R> {
#[cfg(debug_assertions)]
node_id_to_local_id: Default::default(),
trait_map: Default::default(),
next_node_id: resolver.next_node_id,
node_id_to_def_id: NodeMap::default(),
partial_res_overrides: NodeMap::default(),
// Lowering state.
try_block_scope: TryBlockScope::Function,
@@ -237,81 +250,6 @@ impl SpanLowerer {
}
}
struct ResolverDelayedAstLowering<'a, 'tcx> {
node_id_to_def_id: NodeMap<LocalDefId>,
partial_res_map: NodeMap<PartialRes>,
next_node_id: NodeId,
base: &'a ResolverAstLowering<'tcx>,
}
// FIXME(fn_delegation): delegate this trait impl to `self.base`
impl<'a, 'tcx> ResolverAstLoweringExt<'tcx> for ResolverDelayedAstLowering<'a, 'tcx> {
fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'tcx>) -> Option<Vec<usize>> {
self.base.legacy_const_generic_args(expr, tcx)
}
fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
self.partial_res_map.get(&id).copied().or_else(|| self.base.get_partial_res(id))
}
fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
self.base.get_import_res(id)
}
fn get_label_res(&self, id: NodeId) -> Option<NodeId> {
self.base.get_label_res(id)
}
fn get_lifetime_res(&self, id: NodeId) -> Option<LifetimeRes> {
self.base.get_lifetime_res(id)
}
fn extra_lifetime_params(&self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
self.base.extra_lifetime_params(id)
}
fn delegation_info(&self, id: LocalDefId) -> Option<&DelegationInfo> {
self.base.delegation_info(id)
}
fn opt_local_def_id(&self, id: NodeId) -> Option<LocalDefId> {
self.node_id_to_def_id.get(&id).copied().or_else(|| self.base.opt_local_def_id(id))
}
fn local_def_id(&self, id: NodeId) -> LocalDefId {
self.opt_local_def_id(id).expect("must have def_id")
}
fn lifetime_elision_allowed(&self, id: NodeId) -> bool {
self.base.lifetime_elision_allowed(id)
}
fn insert_new_def_id(&mut self, node_id: NodeId, def_id: LocalDefId) {
self.node_id_to_def_id.insert(node_id, def_id);
}
fn insert_partial_res(&mut self, node_id: NodeId, res: PartialRes) {
self.partial_res_map.insert(node_id, res);
}
fn trait_candidates(&self, node_id: NodeId) -> Option<&'tcx [hir::TraitCandidate<'tcx>]> {
self.base.trait_candidates(node_id)
}
#[inline]
fn next_node_id(&mut self) -> NodeId {
next_node_id(&mut self.next_node_id)
}
}
fn next_node_id(current_id: &mut NodeId) -> NodeId {
let start = *current_id;
let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
*current_id = ast::NodeId::from_u32(next);
start
}
#[extension(trait ResolverAstLoweringExt<'tcx>)]
impl<'tcx> ResolverAstLowering<'tcx> {
fn legacy_const_generic_args(&self, expr: &Expr, tcx: TyCtxt<'tcx>) -> Option<Vec<usize>> {
@@ -325,7 +263,10 @@ impl<'tcx> ResolverAstLowering<'tcx> {
return None;
}
let def_id = self.get_partial_res(expr.id)?.full_res()?.opt_def_id()?;
// We do not need to look at `partial_res_overrides`. That map only contains overrides for
// `self_param` locals. And here we are looking for the function definition that `expr`
// resolves to.
let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
// We only support cross-crate argument rewriting. Uses
// within the same crate should be updated to use the new
@@ -342,10 +283,6 @@ impl<'tcx> ResolverAstLowering<'tcx> {
.map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
}
fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
self.partial_res_map.get(&id).copied()
}
/// Obtains per-namespace resolutions for `use` statement with the given `NodeId`.
fn get_import_res(&self, id: NodeId) -> PerNS<Option<Res<NodeId>>> {
self.import_res_map.get(&id).copied().unwrap_or_default()
@@ -368,8 +305,8 @@ impl<'tcx> ResolverAstLowering<'tcx> {
///
/// The extra lifetimes that appear from the parenthesized `Fn`-trait desugaring
/// should appear at the enclosing `PolyTraitRef`.
fn extra_lifetime_params(&self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)> {
self.extra_lifetime_params_map.get(&id).cloned().unwrap_or_default()
fn extra_lifetime_params(&self, id: NodeId) -> &[(Ident, NodeId, LifetimeRes)] {
self.extra_lifetime_params_map.get(&id).map_or(&[], |v| &v[..])
}
fn delegation_info(&self, id: LocalDefId) -> Option<&DelegationInfo> {
@@ -387,23 +324,6 @@ impl<'tcx> ResolverAstLowering<'tcx> {
fn lifetime_elision_allowed(&self, id: NodeId) -> bool {
self.lifetime_elision_allowed.contains(&id)
}
fn insert_new_def_id(&mut self, node_id: NodeId, def_id: LocalDefId) {
self.node_id_to_def_id.insert(node_id, def_id);
}
fn insert_partial_res(&mut self, node_id: NodeId, res: PartialRes) {
self.partial_res_map.insert(node_id, res);
}
fn trait_candidates(&self, node_id: NodeId) -> Option<&'tcx [hir::TraitCandidate<'tcx>]> {
self.trait_map.get(&node_id).copied()
}
#[inline]
fn next_node_id(&mut self) -> NodeId {
next_node_id(&mut self.next_node_id)
}
}
/// How relaxed bounds `?Trait` should be treated.
@@ -544,7 +464,7 @@ enum TryBlockScope {
}
fn index_crate<'a, 'b>(
resolver: &'b impl ResolverAstLoweringExt<'a>,
resolver: &'b ResolverAstLowering<'b>,
krate: &'a Crate,
) -> IndexVec<LocalDefId, AstOwner<'a>> {
let mut indexer = Indexer { resolver, index: IndexVec::new() };
@@ -554,12 +474,12 @@ fn index_crate<'a, 'b>(
return indexer.index;
struct Indexer<'a, 'b, R> {
resolver: &'b R,
struct Indexer<'a, 'b> {
resolver: &'b ResolverAstLowering<'b>,
index: IndexVec<LocalDefId, AstOwner<'a>>,
}
impl<'a, 'b, R: ResolverAstLoweringExt<'a>> visit::Visitor<'a> for Indexer<'a, 'b, R> {
impl<'a, 'b> visit::Visitor<'a> for Indexer<'a, 'b> {
fn visit_attribute(&mut self, _: &'a Attribute) {
// We do not want to lower expressions that appear in attributes,
// as they are not accessible to the rest of the HIR.
@@ -616,7 +536,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
tcx.ensure_done().early_lint_checks(());
tcx.ensure_done().debugger_visualizers(LOCAL_CRATE);
tcx.ensure_done().get_lang_items(());
let (mut resolver, krate) = tcx.resolver_for_lowering().steal();
let (resolver, krate) = tcx.resolver_for_lowering().steal();
let ast_index = index_crate(&resolver, &krate);
let mut owners = IndexVec::from_fn_n(
@@ -626,7 +546,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
let mut lowerer = item::ItemLowerer {
tcx,
resolver: &mut resolver,
resolver: &resolver,
ast_index: &ast_index,
owners: Owners::IndexVec(&mut owners),
};
@@ -634,29 +554,13 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();
for def_id in ast_index.indices() {
let delayed_owner_kind = match &ast_index[def_id] {
AstOwner::Item(Item { kind: ItemKind::Delegation(_), .. }) => {
Some(hir::DelayedOwnerKind::Item)
match &ast_index[def_id] {
AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
delayed_ids.insert(def_id);
}
AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation(_), .. }, ctx) => {
Some(match ctx {
AssocCtxt::Trait => hir::DelayedOwnerKind::TraitItem,
AssocCtxt::Impl { .. } => hir::DelayedOwnerKind::ImplItem,
})
}
_ => None,
_ => lowerer.lower_node(def_id),
};
if let Some(kind) = delayed_owner_kind {
delayed_ids.insert(def_id);
let owner = lowerer.owners.get_or_insert_mut(def_id);
if let hir::MaybeOwner::Phantom = owner {
*owner = hir::MaybeOwner::Delayed(kind)
}
} else {
lowerer.lower_node(def_id);
}
}
// Don't hash unless necessary, because it's expensive.
@@ -677,18 +581,10 @@ pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
// as it is too bad to reindex whole crate on each delegation lowering.
let ast_index = index_crate(resolver, krate);
let mut resolver = ResolverDelayedAstLowering {
next_node_id: resolver.next_node_id,
partial_res_map: Default::default(),
node_id_to_def_id: Default::default(),
base: resolver,
};
let mut map = Default::default();
let mut lowerer = item::ItemLowerer {
tcx,
resolver: &mut resolver,
resolver: &resolver,
ast_index: &ast_index,
owners: Owners::Map(&mut map),
};
@@ -727,13 +623,12 @@ enum GenericArgsMode {
Silence,
}
impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
impl<'hir> LoweringContext<'_, 'hir> {
fn create_def(
&mut self,
node_id: ast::NodeId,
node_id: NodeId,
name: Option<Symbol>,
def_kind: DefKind,
def_path_data: DefPathData,
span: Span,
) -> LocalDefId {
let parent = self.current_hir_id_owner.def_id;
@@ -749,29 +644,42 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
let def_id = self
.tcx
.at(span)
.create_def(parent, name, def_kind, Some(def_path_data), &mut self.disambiguator)
.create_def(parent, name, def_kind, None, &mut self.current_disambiguator)
.def_id();
debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
self.resolver.insert_new_def_id(node_id, def_id);
self.node_id_to_def_id.insert(node_id, def_id);
def_id
}
fn next_node_id(&mut self) -> NodeId {
self.resolver.next_node_id()
let start = self.next_node_id;
let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
self.next_node_id = NodeId::from_u32(next);
start
}
/// Given the id of some node in the AST, finds the `LocalDefId` associated with it by the name
/// resolver (if any).
fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
self.resolver.opt_local_def_id(node)
self.node_id_to_def_id
.get(&node)
.or_else(|| self.resolver.node_id_to_def_id.get(&node))
.copied()
}
fn local_def_id(&self, node: NodeId) -> LocalDefId {
self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
}
fn get_partial_res(&self, id: NodeId) -> Option<PartialRes> {
match self.partial_res_overrides.get(&id) {
Some(self_param_id) => Some(PartialRes::new(Res::Local(*self_param_id))),
None => self.resolver.partial_res_map.get(&id).copied(),
}
}
/// Given the id of an owner node in the AST, returns the corresponding `OwnerId`.
fn owner_id(&self, node: NodeId) -> hir::OwnerId {
hir::OwnerId { def_id: self.local_def_id(node) }
@@ -789,7 +697,16 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
) {
let owner_id = self.owner_id(owner);
let def_id = owner_id.def_id;
let new_disambig = self
.resolver
.disambiguators
.get(&def_id)
.map(|s| s.steal())
.unwrap_or_else(|| PerParentDisambiguatorState::new(def_id));
let disambiguator = std::mem::replace(&mut self.current_disambiguator, new_disambig);
let current_attrs = std::mem::take(&mut self.attrs);
let current_bodies = std::mem::take(&mut self.bodies);
let current_define_opaque = std::mem::take(&mut self.define_opaque);
@@ -824,6 +741,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
assert!(self.impl_trait_bounds.is_empty());
let info = self.make_owner_info(item);
self.current_disambiguator = disambiguator;
self.attrs = current_attrs;
self.bodies = current_bodies;
self.define_opaque = current_define_opaque;
@@ -863,14 +781,12 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
let bodies = SortedMap::from_presorted_elements(bodies);
// Don't hash unless necessary, because it's expensive.
let rustc_middle::hir::Hashes { opt_hash_including_bodies, attrs_hash, delayed_lints_hash } =
self.tcx.hash_owner_nodes(node, &bodies, &attrs, &delayed_lints, define_opaque);
let rustc_middle::hir::Hashes { opt_hash_including_bodies, attrs_hash } =
self.tcx.hash_owner_nodes(node, &bodies, &attrs, define_opaque);
let num_nodes = self.item_local_id_counter.as_usize();
let (nodes, parenting) = index::index_hir(self.tcx, node, &bodies, num_nodes);
let nodes = hir::OwnerNodes { opt_hash_including_bodies, nodes, bodies };
let attrs = hir::AttributeMap { map: attrs, opt_hash: attrs_hash, define_opaque };
let delayed_lints =
hir::lints::DelayedLints { lints: delayed_lints, opt_hash: delayed_lints_hash };
self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map, delayed_lints })
}
@@ -894,8 +810,8 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
}
if let Some(traits) = self.resolver.trait_candidates(ast_node_id) {
self.trait_map.insert(hir_id.local_id, traits);
if let Some(traits) = self.resolver.trait_map.get(&ast_node_id) {
self.trait_map.insert(hir_id.local_id, &traits[..]);
}
// Check whether the same `NodeId` is lowered more than once.
@@ -936,7 +852,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
}
fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {
self.resolver.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
self.get_partial_res(id).map_or(Res::Err, |pr| pr.expect_full_res())
}
fn lower_import_res(&mut self, id: NodeId, span: Span) -> PerNS<Option<Res>> {
@@ -1031,7 +947,6 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
param,
Some(kw::UnderscoreLifetime),
DefKind::LifetimeParam,
DefPathData::DesugaredAnonymousLifetime,
ident.span,
);
debug!(?_def_id);
@@ -1075,8 +990,8 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
let extra_lifetimes = self.resolver.extra_lifetime_params(binder);
debug!(?extra_lifetimes);
let extra_lifetimes: Vec<_> = extra_lifetimes
.into_iter()
.filter_map(|(ident, node_id, res)| {
.iter()
.filter_map(|&(ident, node_id, res)| {
self.lifetime_res_to_generic_param(
ident,
node_id,
@@ -1183,13 +1098,23 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
target,
OmitDoc::Lower,
|s| l.lower(s),
|lint_id, span, kind| {
self.delayed_lints.push(DelayedLint::AttributeParsing(AttributeLint {
lint_id,
id: target_hir_id,
span,
kind,
}));
|lint_id, span, kind| match kind {
EmitAttribute::Static(attr_kind) => {
self.delayed_lints.push(DelayedLint::AttributeParsing(AttributeLint {
lint_id,
id: target_hir_id,
span,
kind: attr_kind,
}));
}
EmitAttribute::Dynamic(callback) => {
self.delayed_lints.push(DelayedLint::Dynamic(DynAttribute {
lint_id,
id: target_hir_id,
span,
callback,
}));
}
},
)
}
@@ -1392,7 +1317,6 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
// FIXME: Should we be handling `(PATH_TO_CONST)`?
TyKind::Path(None, path) => {
if let Some(res) = self
.resolver
.get_partial_res(ty.id)
.and_then(|partial_res| partial_res.full_res())
{
@@ -1443,7 +1367,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
// The other cases when a qpath should be opportunistically made a trait object are handled
// by `ty_path`.
if qself.is_none()
&& let Some(partial_res) = self.resolver.get_partial_res(t.id)
&& let Some(partial_res) = self.get_partial_res(t.id)
&& let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
{
let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| {
@@ -1797,7 +1721,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
let [segment] = path.segments.as_slice() else {
panic!();
};
let res = self.resolver.get_partial_res(*id).map_or(Res::Err, |partial_res| {
let res = self.get_partial_res(*id).map_or(Res::Err, |partial_res| {
partial_res.full_res().expect("no partial res expected for precise capture arg")
});
hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
@@ -1848,7 +1772,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
// as they are not explicit in HIR/Ty function signatures.
// (instead, the `c_variadic` flag is set to `true`)
let mut inputs = &decl.inputs[..];
if c_variadic {
if decl.c_variadic() {
inputs = &inputs[..inputs.len() - 1];
}
let inputs = self.arena.alloc_from_iter(inputs.iter().map(|param| {
@@ -1911,12 +1835,8 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
},
};
self.arena.alloc(hir::FnDecl {
inputs,
output,
c_variadic,
lifetime_elision_allowed: self.resolver.lifetime_elision_allowed(fn_node_id),
implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
let fn_decl_kind = hir::FnDeclFlags::default()
.set_implicit_self(decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| {
let is_mutable_pat = matches!(
arg.pat.kind,
PatKind::Ident(hir::BindingMode(_, Mutability::Mut), ..)
@@ -1938,8 +1858,11 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
}
_ => hir::ImplicitSelfKind::None,
}
}),
})
}))
.set_lifetime_elision_allowed(self.resolver.lifetime_elision_allowed(fn_node_id))
.set_c_variadic(c_variadic);
self.arena.alloc(hir::FnDecl { inputs, output, fn_decl_kind })
}
// Transforms `-> T` for `async fn` into `-> OpaqueTy { .. }`
@@ -2236,14 +2159,22 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
// since later compiler stages cannot handle them (and shouldn't need to be able to).
let default = default
.as_ref()
.filter(|_| match source {
.filter(|anon_const| match source {
hir::GenericParamSource::Generics => true,
hir::GenericParamSource::Binder => {
self.dcx().emit_err(errors::GenericParamDefaultInBinder {
span: param.span(),
});
false
let err = errors::GenericParamDefaultInBinder { span: param.span() };
if expr::WillCreateDefIdsVisitor
.visit_expr(&anon_const.value)
.is_break()
{
// FIXME(mgca): make this non-fatal once we have a better way
// to handle nested items in anno const from binder
// Issue: https://github.com/rust-lang/rust/issues/123629
self.dcx().emit_fatal(err)
} else {
self.dcx().emit_err(err);
false
}
}
})
.map(|def| self.lower_anon_const_to_const_arg_and_alloc(def));
@@ -2319,7 +2250,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
match rbp {
RelaxedBoundPolicy::Allowed => return,
RelaxedBoundPolicy::AllowedIfOnTyParam(id, params) => {
if let Some(res) = self.resolver.get_partial_res(id).and_then(|r| r.full_res())
if let Some(res) = self.get_partial_res(id).and_then(|r| r.full_res())
&& let Res::Def(DefKind::TyParam, def_id) = res
&& params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id())
{
@@ -2512,13 +2443,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
// We're lowering a const argument that was originally thought to be a type argument,
// so the def collector didn't create the def ahead of time. That's why we have to do
// it here.
let def_id = self.create_def(
node_id,
None,
DefKind::AnonConst,
DefPathData::LateAnonConst,
span,
);
let def_id = self.create_def(node_id, None, DefKind::AnonConst, span);
let hir_id = self.lower_node_id(node_id);
let path_expr = Expr {
@@ -2580,12 +2505,17 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
let span = self.lower_span(expr.span);
let overly_complex_const = |this: &mut Self| {
let e = this.dcx().struct_span_err(
expr.span,
"complex const arguments must be placed inside of a `const` block",
);
let msg = "complex const arguments must be placed inside of a `const` block";
let e = if expr::WillCreateDefIdsVisitor.visit_expr(expr).is_break() {
// FIXME(mgca): make this non-fatal once we have a better way to handle
// nested items in const args
// Issue: https://github.com/rust-lang/rust/issues/154539
this.dcx().struct_span_fatal(expr.span, msg).emit()
} else {
this.dcx().struct_span_err(expr.span, msg).emit()
};
ConstArg { hir_id: this.next_id(), kind: hir::ConstArgKind::Error(e.emit()), span }
ConstArg { hir_id: this.next_id(), kind: hir::ConstArgKind::Error(e), span }
};
match &expr.kind {
@@ -2790,7 +2720,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
};
let maybe_res =
self.resolver.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res());
self.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res());
if let ExprKind::Path(qself, path) = &expr.kind
&& path.is_potential_trivial_const_arg()
&& matches!(maybe_res, Some(Res::Def(DefKind::ConstParam, _)))
@@ -3102,10 +3032,7 @@ impl<'hir> GenericArgsCtor<'hir> {
&& self.parenthesized == hir::GenericArgsParentheses::No
}
fn into_generic_args(
self,
this: &LoweringContext<'_, 'hir, impl ResolverAstLoweringExt<'hir>>,
) -> &'hir hir::GenericArgs<'hir> {
fn into_generic_args(self, this: &LoweringContext<'_, 'hir>) -> &'hir hir::GenericArgs<'hir> {
let ga = hir::GenericArgs {
args: this.arena.alloc_from_iter(self.args),
constraints: self.constraints,

View File

@@ -3,7 +3,6 @@ use std::sync::Arc;
use rustc_ast::*;
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::definitions::DefPathData;
use rustc_hir::{self as hir, LangItem, Target};
use rustc_middle::span_bug;
use rustc_span::{DesugaringKind, Ident, Span, Spanned, respan};
@@ -11,10 +10,11 @@ use rustc_span::{DesugaringKind, Ident, Span, Spanned, respan};
use super::errors::{
ArbitraryExpressionInPattern, ExtraDoubleDot, MisplacedDoubleDot, SubTupleBinding,
};
use super::{ImplTraitContext, LoweringContext, ParamMode, ResolverAstLoweringExt};
use crate::{AllowReturnTypeNotation, ImplTraitPosition};
use super::{
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
};
impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
impl<'hir> LoweringContext<'_, 'hir> {
pub(crate) fn lower_pat(&mut self, pattern: &Pat) -> &'hir hir::Pat<'hir> {
self.arena.alloc(self.lower_pat_mut(pattern))
}
@@ -288,7 +288,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
hir_id: hir::HirId,
lower_sub: impl FnOnce(&mut Self) -> Option<&'hir hir::Pat<'hir>>,
) -> hir::PatKind<'hir> {
match self.resolver.get_partial_res(p.id).map(|d| d.expect_full_res()) {
match self.get_partial_res(p.id).map(|d| d.expect_full_res()) {
// `None` can occur in body-less function signatures
res @ (None | Some(Res::Local(_))) => {
let binding_id = match res {
@@ -538,8 +538,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
// We're generating a range end that didn't exist in the AST,
// so the def collector didn't create the def ahead of time. That's why we have to do
// it here.
let def_id =
self.create_def(node_id, None, DefKind::AnonConst, DefPathData::LateAnonConst, span);
let def_id = self.create_def(node_id, None, DefKind::AnonConst, span);
let hir_id = self.lower_node_id(node_id);
let unstable_span = self.mark_span_with_reason(

View File

@@ -20,7 +20,7 @@ use super::{
LifetimeRes, LoweringContext, ParamMode, ResolverAstLoweringExt,
};
impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
impl<'hir> LoweringContext<'_, 'hir> {
#[instrument(level = "trace", skip(self))]
pub(crate) fn lower_qpath(
&mut self,
@@ -41,8 +41,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
self.lower_ty_alloc(&q.ty, ImplTraitContext::Disallowed(ImplTraitPosition::Path))
});
let partial_res =
self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
let partial_res = self.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err));
let base_res = partial_res.base_res();
let unresolved_segments = partial_res.unresolved_segments();

View File

@@ -18,5 +18,5 @@ rustc_macros = { path = "../rustc_macros" }
rustc_session = { path = "../rustc_session" }
rustc_span = { path = "../rustc_span" }
rustc_target = { path = "../rustc_target" }
thin-vec = "0.2.12"
thin-vec = "0.2.15"
# tidy-alphabetical-end

View File

@@ -208,7 +208,7 @@ impl<'a> AstValidator<'a> {
}
// Mirrors `visit::walk_ty`, but tracks relevant state.
fn walk_ty(&mut self, t: &'a Ty) {
fn walk_ty(&mut self, t: &Ty) {
match &t.kind {
TyKind::ImplTrait(_, bounds) => {
self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t));
@@ -731,7 +731,7 @@ impl<'a> AstValidator<'a> {
/// C-variadics must be:
/// - Non-const
/// - Either foreign, or free and `unsafe extern "C"` semantically
fn check_c_variadic_type(&self, fk: FnKind<'a>, attrs: &'a AttrVec) {
fn check_c_variadic_type(&self, fk: FnKind<'_>, attrs: &AttrVec) {
// `...` is already rejected when it is not the final parameter.
let variadic_param = match fk.decl().inputs.last() {
Some(param) if matches!(param.ty.kind, TyKind::CVarArgs) => param,
@@ -806,7 +806,7 @@ impl<'a> AstValidator<'a> {
fn check_c_variadic_abi(
&self,
abi: ExternAbi,
attrs: &'a AttrVec,
attrs: &AttrVec,
dotdotdot_span: Span,
sig: &FnSig,
) {
@@ -976,7 +976,7 @@ impl<'a> AstValidator<'a> {
});
}
fn visit_ty_common(&mut self, ty: &'a Ty) {
fn visit_ty_common(&mut self, ty: &Ty) {
match &ty.kind {
TyKind::FnPtr(bfty) => {
self.check_fn_ptr_safety(bfty.decl_span, bfty.safety);
@@ -1039,13 +1039,13 @@ impl<'a> AstValidator<'a> {
}
// Used within `visit_item` for item kinds where we don't call `visit::walk_item`.
fn visit_attrs_vis(&mut self, attrs: &'a AttrVec, vis: &'a Visibility) {
fn visit_attrs_vis(&mut self, attrs: &AttrVec, vis: &Visibility) {
walk_list!(self, visit_attribute, attrs);
self.visit_vis(vis);
}
// Used within `visit_item` for item kinds where we don't call `visit::walk_item`.
fn visit_attrs_vis_ident(&mut self, attrs: &'a AttrVec, vis: &'a Visibility, ident: &'a Ident) {
fn visit_attrs_vis_ident(&mut self, attrs: &AttrVec, vis: &Visibility, ident: &Ident) {
walk_list!(self, visit_attribute, attrs);
self.visit_vis(vis);
self.visit_ident(ident);
@@ -1125,17 +1125,17 @@ fn validate_generic_param_order(dcx: DiagCtxtHandle<'_>, generics: &[GenericPara
}
}
impl<'a> Visitor<'a> for AstValidator<'a> {
impl Visitor<'_> for AstValidator<'_> {
fn visit_attribute(&mut self, attr: &Attribute) {
validate_attr::check_attr(&self.sess.psess, attr);
}
fn visit_ty(&mut self, ty: &'a Ty) {
fn visit_ty(&mut self, ty: &Ty) {
self.visit_ty_common(ty);
self.walk_ty(ty)
}
fn visit_item(&mut self, item: &'a Item) {
fn visit_item(&mut self, item: &Item) {
if item.attrs.iter().any(|attr| attr.is_proc_macro_attr()) {
self.has_proc_macro_decls = true;
}
@@ -1477,7 +1477,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
self.lint_node_id = previous_lint_node_id;
}
fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
fn visit_foreign_item(&mut self, fi: &ForeignItem) {
match &fi.kind {
ForeignItemKind::Fn(box Fn { defaultness, ident, sig, body, .. }) => {
self.check_defaultness(fi.span, *defaultness, AllowDefault::No, AllowFinal::No);
@@ -1527,7 +1527,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
}
// Mirrors `visit::walk_generic_args`, but tracks relevant state.
fn visit_generic_args(&mut self, generic_args: &'a GenericArgs) {
fn visit_generic_args(&mut self, generic_args: &GenericArgs) {
match generic_args {
GenericArgs::AngleBracketed(data) => {
self.check_generic_args_before_constraints(data);
@@ -1557,7 +1557,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
}
}
fn visit_generics(&mut self, generics: &'a Generics) {
fn visit_generics(&mut self, generics: &Generics) {
let mut prev_param_default = None;
for param in &generics.params {
match param.kind {
@@ -1613,7 +1613,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
}
}
fn visit_param_bound(&mut self, bound: &'a GenericBound, ctxt: BoundKind) {
fn visit_param_bound(&mut self, bound: &GenericBound, ctxt: BoundKind) {
match bound {
GenericBound::Trait(trait_ref) => {
match (ctxt, trait_ref.modifiers.constness, trait_ref.modifiers.polarity) {
@@ -1671,7 +1671,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
visit::walk_param_bound(self, bound)
}
fn visit_fn(&mut self, fk: FnKind<'a>, attrs: &AttrVec, span: Span, id: NodeId) {
fn visit_fn(&mut self, fk: FnKind<'_>, attrs: &AttrVec, span: Span, id: NodeId) {
// Only associated `fn`s can have `self` parameters.
let self_semantic = match fk.ctxt() {
Some(FnCtxt::Assoc(_)) => SelfSemantic::Yes,
@@ -1784,7 +1784,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
self.with_tilde_const(disallowed, |this| visit::walk_fn(this, fk));
}
fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
fn visit_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) {
if let Some(ident) = item.kind.ident()
&& attr::contains_name(&item.attrs, sym::no_mangle)
{
@@ -1931,7 +1931,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
}
}
fn visit_anon_const(&mut self, anon_const: &'a AnonConst) {
fn visit_anon_const(&mut self, anon_const: &AnonConst) {
self.with_tilde_const(
Some(TildeConstReason::AnonConst { span: anon_const.value.span }),
|this| visit::walk_anon_const(this, anon_const),

View File

@@ -7,7 +7,7 @@ use rustc_hir::Attribute;
use rustc_hir::attrs::AttributeKind;
use rustc_session::Session;
use rustc_session::parse::{feature_err, feature_warn};
use rustc_span::{DUMMY_SP, Span, Spanned, Symbol, sym};
use rustc_span::{Span, Spanned, Symbol, sym};
use thin_vec::ThinVec;
use crate::errors;
@@ -646,14 +646,7 @@ fn maybe_stage_features(sess: &Session, features: &Features, krate: &ast::Crate)
let mut errored = false;
if let Some(Attribute::Parsed(AttributeKind::Feature(feature_idents, first_span))) =
AttributeParser::parse_limited(
sess,
&krate.attrs,
&[sym::feature],
DUMMY_SP,
krate.id,
Some(&features),
)
AttributeParser::parse_limited(sess, &krate.attrs, &[sym::feature])
{
// `feature(...)` used on non-nightly. This is definitely an error.
let mut err = errors::FeatureOnNonNightly {

View File

@@ -13,5 +13,5 @@ rustc_span = { path = "../rustc_span" }
[dev-dependencies]
# tidy-alphabetical-start
thin-vec = "0.2.12"
thin-vec = "0.2.15"
# tidy-alphabetical-end

View File

@@ -1,49 +0,0 @@
use std::borrow::Cow;
use crate::pp::Printer;
impl Printer {
pub fn word_space<W: Into<Cow<'static, str>>>(&mut self, w: W) {
self.word(w);
self.space();
}
pub fn popen(&mut self) {
self.word("(");
}
pub fn pclose(&mut self) {
self.word(")");
}
pub fn hardbreak_if_not_bol(&mut self) {
if !self.is_beginning_of_line() {
self.hardbreak()
}
}
pub fn space_if_not_bol(&mut self) {
if !self.is_beginning_of_line() {
self.space();
}
}
pub fn nbsp(&mut self) {
self.word(" ")
}
pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
self.word(w);
self.nbsp()
}
/// Synthesizes a comment that was not textually present in the original
/// source file.
pub fn synth_comment(&mut self, text: impl Into<Cow<'static, str>>) {
self.word("/*");
self.space();
self.word(text);
self.space();
self.word("*/")
}
}

View File

@@ -3,6 +3,5 @@
#![feature(negative_impls)]
// tidy-alphabetical-end
mod helpers;
pub mod pp;
pub mod pprust;

View File

@@ -132,7 +132,6 @@
//! methods called `Printer::scan_*`, and the 'PRINT' process is the
//! method called `Printer::print`.
mod convenience;
mod ring;
use std::borrow::Cow;
@@ -188,6 +187,12 @@ pub(crate) enum Token {
End,
}
impl Token {
pub(crate) fn is_hardbreak_tok(&self) -> bool {
*self == Printer::hardbreak_tok_offset(0)
}
}
#[derive(Copy, Clone)]
enum PrintFrame {
Fits,
@@ -479,4 +484,132 @@ impl Printer {
self.out.push_str(string);
self.space -= string.len() as isize;
}
/// Synthesizes a comment that was not textually present in the original
/// source file.
pub fn synth_comment(&mut self, text: impl Into<Cow<'static, str>>) {
self.word("/*");
self.space();
self.word(text);
self.space();
self.word("*/")
}
/// "raw box"
pub fn rbox(&mut self, indent: isize, breaks: Breaks) -> BoxMarker {
self.scan_begin(BeginToken { indent: IndentStyle::Block { offset: indent }, breaks })
}
/// Inconsistent breaking box
pub fn ibox(&mut self, indent: isize) -> BoxMarker {
self.rbox(indent, Breaks::Inconsistent)
}
/// Consistent breaking box
pub fn cbox(&mut self, indent: isize) -> BoxMarker {
self.rbox(indent, Breaks::Consistent)
}
pub fn visual_align(&mut self) -> BoxMarker {
self.scan_begin(BeginToken { indent: IndentStyle::Visual, breaks: Breaks::Consistent })
}
pub fn break_offset(&mut self, n: usize, off: isize) {
self.scan_break(BreakToken {
offset: off,
blank_space: n as isize,
..BreakToken::default()
});
}
pub fn end(&mut self, b: BoxMarker) {
self.scan_end(b)
}
pub fn eof(mut self) -> String {
self.scan_eof();
self.out
}
pub fn word<S: Into<Cow<'static, str>>>(&mut self, wrd: S) {
let string = wrd.into();
self.scan_string(string)
}
pub fn word_space<W: Into<Cow<'static, str>>>(&mut self, w: W) {
self.word(w);
self.space();
}
pub fn nbsp(&mut self) {
self.word(" ")
}
pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
self.word(w);
self.nbsp()
}
fn spaces(&mut self, n: usize) {
self.break_offset(n, 0)
}
pub fn zerobreak(&mut self) {
self.spaces(0)
}
pub fn space(&mut self) {
self.spaces(1)
}
pub fn popen(&mut self) {
self.word("(");
}
pub fn pclose(&mut self) {
self.word(")");
}
pub fn hardbreak(&mut self) {
self.spaces(SIZE_INFINITY as usize)
}
pub fn is_beginning_of_line(&self) -> bool {
match self.last_token() {
Some(last_token) => last_token.is_hardbreak_tok(),
None => true,
}
}
pub fn hardbreak_if_not_bol(&mut self) {
if !self.is_beginning_of_line() {
self.hardbreak()
}
}
pub fn space_if_not_bol(&mut self) {
if !self.is_beginning_of_line() {
self.space();
}
}
pub(crate) fn hardbreak_tok_offset(off: isize) -> Token {
Token::Break(BreakToken {
offset: off,
blank_space: SIZE_INFINITY,
..BreakToken::default()
})
}
pub fn trailing_comma(&mut self) {
self.scan_break(BreakToken { pre_break: Some(','), ..BreakToken::default() });
}
pub fn trailing_comma_or_space(&mut self) {
self.scan_break(BreakToken {
blank_space: 1,
pre_break: Some(','),
..BreakToken::default()
});
}
}

View File

@@ -1,97 +0,0 @@
use std::borrow::Cow;
use crate::pp::{
BeginToken, BoxMarker, BreakToken, Breaks, IndentStyle, Printer, SIZE_INFINITY, Token,
};
impl Printer {
/// "raw box"
pub fn rbox(&mut self, indent: isize, breaks: Breaks) -> BoxMarker {
self.scan_begin(BeginToken { indent: IndentStyle::Block { offset: indent }, breaks })
}
/// Inconsistent breaking box
pub fn ibox(&mut self, indent: isize) -> BoxMarker {
self.rbox(indent, Breaks::Inconsistent)
}
/// Consistent breaking box
pub fn cbox(&mut self, indent: isize) -> BoxMarker {
self.rbox(indent, Breaks::Consistent)
}
pub fn visual_align(&mut self) -> BoxMarker {
self.scan_begin(BeginToken { indent: IndentStyle::Visual, breaks: Breaks::Consistent })
}
pub fn break_offset(&mut self, n: usize, off: isize) {
self.scan_break(BreakToken {
offset: off,
blank_space: n as isize,
..BreakToken::default()
});
}
pub fn end(&mut self, b: BoxMarker) {
self.scan_end(b)
}
pub fn eof(mut self) -> String {
self.scan_eof();
self.out
}
pub fn word<S: Into<Cow<'static, str>>>(&mut self, wrd: S) {
let string = wrd.into();
self.scan_string(string)
}
fn spaces(&mut self, n: usize) {
self.break_offset(n, 0)
}
pub fn zerobreak(&mut self) {
self.spaces(0)
}
pub fn space(&mut self) {
self.spaces(1)
}
pub fn hardbreak(&mut self) {
self.spaces(SIZE_INFINITY as usize)
}
pub fn is_beginning_of_line(&self) -> bool {
match self.last_token() {
Some(last_token) => last_token.is_hardbreak_tok(),
None => true,
}
}
pub(crate) fn hardbreak_tok_offset(off: isize) -> Token {
Token::Break(BreakToken {
offset: off,
blank_space: SIZE_INFINITY,
..BreakToken::default()
})
}
pub fn trailing_comma(&mut self) {
self.scan_break(BreakToken { pre_break: Some(','), ..BreakToken::default() });
}
pub fn trailing_comma_or_space(&mut self) {
self.scan_break(BreakToken {
blank_space: 1,
pre_break: Some(','),
..BreakToken::default()
});
}
}
impl Token {
pub(crate) fn is_hardbreak_tok(&self) -> bool {
*self == Printer::hardbreak_tok_offset(0)
}
}

View File

@@ -43,6 +43,7 @@ impl<'a> State<'a> {
expr,
safety,
define_opaque,
eii_impls,
}) => self.print_item_const(
*ident,
Some(*mutability),
@@ -53,6 +54,7 @@ impl<'a> State<'a> {
*safety,
ast::Defaultness::Implicit,
define_opaque.as_deref(),
eii_impls,
),
ast::ForeignItemKind::TyAlias(box ast::TyAlias {
defaultness,
@@ -93,8 +95,12 @@ impl<'a> State<'a> {
safety: ast::Safety,
defaultness: ast::Defaultness,
define_opaque: Option<&[(ast::NodeId, ast::Path)]>,
eii_impls: &[EiiImpl],
) {
self.print_define_opaques(define_opaque);
for eii_impl in eii_impls {
self.print_eii_impl(eii_impl);
}
let (cb, ib) = self.head("");
self.print_visibility(vis);
self.print_safety(safety);
@@ -191,6 +197,7 @@ impl<'a> State<'a> {
mutability: mutbl,
expr: body,
define_opaque,
eii_impls,
}) => {
self.print_safety(*safety);
self.print_item_const(
@@ -203,6 +210,7 @@ impl<'a> State<'a> {
ast::Safety::Default,
ast::Defaultness::Implicit,
define_opaque.as_deref(),
eii_impls,
);
}
ast::ItemKind::ConstBlock(ast::ConstBlockItem { id: _, span: _, block }) => {
@@ -234,6 +242,7 @@ impl<'a> State<'a> {
ast::Safety::Default,
*defaultness,
define_opaque.as_deref(),
&[],
);
}
ast::ItemKind::Fn(func) => {
@@ -362,10 +371,10 @@ impl<'a> State<'a> {
self.bclose(item.span, empty, cb);
}
ast::ItemKind::Trait(box ast::Trait {
impl_restriction,
constness,
safety,
is_auto,
impl_restriction,
ident,
generics,
bounds,
@@ -373,10 +382,10 @@ impl<'a> State<'a> {
}) => {
let (cb, ib) = self.head("");
self.print_visibility(&item.vis);
self.print_impl_restriction(impl_restriction);
self.print_constness(*constness);
self.print_safety(*safety);
self.print_is_auto(*is_auto);
self.print_impl_restriction(impl_restriction);
self.word_nbsp("trait");
self.print_ident(*ident);
self.print_generic_params(&generics.params);
@@ -435,7 +444,10 @@ impl<'a> State<'a> {
&item.vis,
&deleg.qself,
&deleg.prefix,
deleg.suffixes.as_ref().map_or(DelegationKind::Glob, |s| DelegationKind::List(s)),
match &deleg.suffixes {
ast::DelegationSuffixes::List(s) => DelegationKind::List(s),
ast::DelegationSuffixes::Glob(_) => DelegationKind::Glob,
},
&deleg.body,
),
}
@@ -602,6 +614,7 @@ impl<'a> State<'a> {
ast::Safety::Default,
*defaultness,
define_opaque.as_deref(),
&[],
);
}
ast::AssocItemKind::Type(box ast::TyAlias {
@@ -641,7 +654,10 @@ impl<'a> State<'a> {
vis,
&deleg.qself,
&deleg.prefix,
deleg.suffixes.as_ref().map_or(DelegationKind::Glob, |s| DelegationKind::List(s)),
match &deleg.suffixes {
ast::DelegationSuffixes::List(s) => DelegationKind::List(s),
ast::DelegationSuffixes::Glob(_) => DelegationKind::Glob,
},
&deleg.body,
),
}
@@ -703,18 +719,8 @@ impl<'a> State<'a> {
self.print_define_opaques(define_opaque.as_deref());
for EiiImpl { eii_macro_path, impl_safety, .. } in eii_impls {
self.word("#[");
if let Safety::Unsafe(..) = impl_safety {
self.word("unsafe");
self.popen();
}
self.print_path(eii_macro_path, false, 0);
if let Safety::Unsafe(..) = impl_safety {
self.pclose();
}
self.word("]");
self.hardbreak();
for eii_impl in eii_impls {
self.print_eii_impl(eii_impl);
}
let body_cb_ib = body.as_ref().map(|body| (body, self.head("")));
@@ -741,6 +747,20 @@ impl<'a> State<'a> {
}
}
fn print_eii_impl(&mut self, eii: &ast::EiiImpl) {
self.word("#[");
if let Safety::Unsafe(..) = eii.impl_safety {
self.word("unsafe");
self.popen();
}
self.print_path(&eii.eii_macro_path, false, 0);
if let Safety::Unsafe(..) = eii.impl_safety {
self.pclose();
}
self.word("]");
self.hardbreak();
}
fn print_define_opaques(&mut self, define_opaque: Option<&[(ast::NodeId, ast::Path)]>) {
if let Some(define_opaque) = define_opaque {
self.word("#[define_opaque(");

View File

@@ -19,5 +19,5 @@ rustc_parse_format = { path = "../rustc_parse_format" }
rustc_session = { path = "../rustc_session" }
rustc_span = { path = "../rustc_span" }
rustc_target = { path = "../rustc_target" }
thin-vec = "0.2.12"
thin-vec = "0.2.15"
# tidy-alphabetical-end

View File

@@ -81,7 +81,7 @@ fn parse_unstable<S: Stage>(
) -> impl IntoIterator<Item = Symbol> {
let mut res = Vec::new();
let Some(list) = args.list() else {
let Some(list) = args.as_list() else {
cx.emit_err(session_diagnostics::ExpectsFeatureList {
span: cx.attr_span,
name: symbol.to_ident_string(),

View File

@@ -8,8 +8,8 @@ use rustc_hir::{MethodKind, Target};
use rustc_span::{Symbol, sym};
use thin_vec::ThinVec;
use crate::attributes::SingleAttributeParser;
use crate::attributes::prelude::Allow;
use crate::attributes::{OnDuplicate, SingleAttributeParser};
use crate::context::{AcceptContext, Stage};
use crate::parser::{ArgParser, MetaItemOrLitParser};
use crate::target_checking::AllowedTargets;
@@ -18,7 +18,6 @@ pub(crate) struct RustcAutodiffParser;
impl<S: Stage> SingleAttributeParser<S> for RustcAutodiffParser {
const PATH: &[Symbol] = &[sym::rustc_autodiff];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),

View File

@@ -6,7 +6,6 @@ pub(crate) struct CoroutineParser;
impl<S: Stage> NoArgsAttributeParser<S> for CoroutineParser {
const PATH: &[Symbol] = &[sym::coroutine];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Closure)]);
const CREATE: fn(rustc_span::Span) -> AttributeKind = |span| AttributeKind::Coroutine(span);
}

View File

@@ -2,7 +2,7 @@ use std::convert::identity;
use rustc_ast::token::Delimiter;
use rustc_ast::tokenstream::DelimSpan;
use rustc_ast::{AttrItem, Attribute, CRATE_NODE_ID, LitKind, ast, token};
use rustc_ast::{AttrItem, Attribute, LitKind, ast, token};
use rustc_errors::{Applicability, PResult, msg};
use rustc_feature::{
AttrSuggestionStyle, AttributeTemplate, Features, GatedCfg, find_gated_cfg, template,
@@ -19,6 +19,7 @@ use rustc_session::parse::{ParseSess, feature_err};
use rustc_span::{ErrorGuaranteed, Span, Symbol, sym};
use thin_vec::ThinVec;
use crate::attributes::AttributeSafety;
use crate::context::{AcceptContext, ShouldEmit, Stage};
use crate::parser::{
AllowExprMetavar, ArgParser, MetaItemListParser, MetaItemOrLitParser, NameValueParser,
@@ -43,13 +44,9 @@ pub fn parse_cfg<S: Stage>(
cx: &mut AcceptContext<'_, '_, S>,
args: &ArgParser,
) -> Option<CfgEntry> {
let ArgParser::List(list) = args else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let list = cx.expect_list(args, cx.attr_span)?;
let Some(single) = list.single() else {
let Some(single) = list.as_single() else {
let target = cx.target;
let mut adcx = cx.adcx();
if list.is_empty() {
@@ -78,7 +75,7 @@ pub fn parse_cfg<S: Stage>(
}
}
adcx.expected_single_argument(list.span);
adcx.expected_single_argument(list.span, list.len());
return None;
};
parse_cfg_entry(cx, single).ok()
@@ -92,8 +89,8 @@ pub fn parse_cfg_entry<S: Stage>(
MetaItemOrLitParser::MetaItemParser(meta) => match meta.args() {
ArgParser::List(list) => match meta.path().word_sym() {
Some(sym::not) => {
let Some(single) = list.single() else {
return Err(cx.adcx().expected_single_argument(list.span));
let Some(single) = list.as_single() else {
return Err(cx.adcx().expected_single_argument(list.span, list.len()));
};
CfgEntry::Not(Box::new(parse_cfg_entry(cx, single)?), list.span)
}
@@ -135,7 +132,7 @@ fn parse_cfg_entry_version<S: Stage>(
meta_span: Span,
) -> Result<CfgEntry, ErrorGuaranteed> {
try_gate_cfg(sym::version, meta_span, cx.sess(), cx.features_option());
let Some(version) = list.single() else {
let Some(version) = list.as_single() else {
return Err(
cx.emit_err(session_diagnostics::ExpectedSingleVersionLiteral { span: list.span })
);
@@ -324,12 +321,13 @@ pub fn parse_cfg_attr(
cfg_attr: &Attribute,
sess: &Session,
features: Option<&Features>,
lint_node_id: ast::NodeId,
) -> Option<(CfgEntry, Vec<(AttrItem, Span)>)> {
match cfg_attr.get_normal_item().args.unparsed_ref().unwrap() {
ast::AttrArgs::Delimited(ast::DelimArgs { dspan, delim, tokens }) if !tokens.is_empty() => {
check_cfg_attr_bad_delim(&sess.psess, *dspan, *delim);
match parse_in(&sess.psess, tokens.clone(), "`cfg_attr` input", |p| {
parse_cfg_attr_internal(p, sess, features, cfg_attr)
parse_cfg_attr_internal(p, sess, features, lint_node_id, cfg_attr)
}) {
Ok(r) => return Some(r),
Err(e) => {
@@ -390,6 +388,7 @@ fn parse_cfg_attr_internal<'a>(
parser: &mut Parser<'a>,
sess: &'a Session,
features: Option<&Features>,
lint_node_id: ast::NodeId,
attribute: &Attribute,
) -> PResult<'a, (CfgEntry, Vec<(ast::AttrItem, Span)>)> {
// Parse cfg predicate
@@ -408,9 +407,10 @@ fn parse_cfg_attr_internal<'a>(
attribute.style,
AttrPath { segments: attribute.path().into_boxed_slice(), span: attribute.span },
Some(attribute.get_normal_item().unsafety),
AttributeSafety::Normal,
ParsedDescription::Attribute,
pred_span,
CRATE_NODE_ID,
lint_node_id,
Target::Crate,
features,
ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },

View File

@@ -12,6 +12,7 @@ use rustc_session::Session;
use rustc_session::lint::builtin::UNREACHABLE_CFG_SELECT_PREDICATES;
use rustc_span::{ErrorGuaranteed, Span, Symbol, sym};
use crate::attributes::AttributeSafety;
use crate::parser::{AllowExprMetavar, MetaItemOrLitParser};
use crate::{AttributeParser, ParsedDescription, ShouldEmit, errors, parse_cfg_entry};
@@ -105,6 +106,7 @@ pub fn parse_cfg_select(
AttrStyle::Inner,
AttrPath { segments: vec![sym::cfg_select].into_boxed_slice(), span: cfg_span },
None,
AttributeSafety::Normal,
ParsedDescription::Macro,
cfg_span,
lint_node_id,

View File

@@ -8,7 +8,6 @@ impl<S: Stage> SingleAttributeParser<S> for CfiEncodingParser {
Allow(Target::Enum),
Allow(Target::Union),
]);
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const TEMPLATE: AttributeTemplate = template!(NameValueStr: "encoding");
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {

View File

@@ -1,7 +1,9 @@
use rustc_hir::attrs::{CoverageAttrKind, OptimizeAttr, RtsanSetting, SanitizerSet, UsedBy};
use rustc_session::parse::feature_err;
use rustc_span::edition::Edition::Edition2024;
use super::prelude::*;
use crate::attributes::AttributeSafety;
use crate::session_diagnostics::{
NakedFunctionIncompatibleAttribute, NullOnExport, NullOnObjcClass, NullOnObjcSelector,
ObjcClassExpectedStringLiteral, ObjcSelectorExpectedStringLiteral,
@@ -12,7 +14,6 @@ pub(crate) struct OptimizeParser;
impl<S: Stage> SingleAttributeParser<S> for OptimizeParser {
const PATH: &[Symbol] = &[sym::optimize];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::WarnButFutureError;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Closure),
@@ -23,16 +24,7 @@ impl<S: Stage> SingleAttributeParser<S> for OptimizeParser {
const TEMPLATE: AttributeTemplate = template!(List: &["size", "speed", "none"]);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let Some(single) = list.single() else {
cx.adcx().expected_single_argument(list.span);
return None;
};
let single = cx.expect_single_element_list(args, cx.attr_span)?;
let res = match single.meta_item().and_then(|i| i.path().word().map(|i| i.name)) {
Some(sym::size) => OptimizeAttr::Size,
@@ -69,7 +61,6 @@ pub(crate) struct CoverageParser;
impl<S: Stage> SingleAttributeParser<S> for CoverageParser {
const PATH: &[Symbol] = &[sym::coverage];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Closure),
@@ -84,22 +75,13 @@ impl<S: Stage> SingleAttributeParser<S> for CoverageParser {
const TEMPLATE: AttributeTemplate = template!(OneOf: &[sym::off, sym::on]);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(args) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_specific_argument_and_list(attr_span, &[sym::on, sym::off]);
return None;
};
let Some(arg) = args.single() else {
cx.adcx().expected_single_argument(args.span);
return None;
};
let arg = cx.expect_single_element_list(args, cx.attr_span)?;
let mut fail_incorrect_argument =
|span| cx.adcx().expected_specific_argument(span, &[sym::on, sym::off]);
let Some(arg) = arg.meta_item() else {
fail_incorrect_argument(args.span);
fail_incorrect_argument(arg.span());
return None;
};
@@ -121,6 +103,7 @@ pub(crate) struct ExportNameParser;
impl<S: Stage> SingleAttributeParser<S> for ExportNameParser {
const PATH: &[rustc_span::Symbol] = &[sym::export_name];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::WarnButFutureError;
const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: Some(Edition2024) };
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Static),
Allow(Target::Fn),
@@ -158,7 +141,6 @@ pub(crate) struct RustcObjcClassParser;
impl<S: Stage> SingleAttributeParser<S> for RustcObjcClassParser {
const PATH: &[rustc_span::Symbol] = &[sym::rustc_objc_class];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::ForeignStatic)]);
const TEMPLATE: AttributeTemplate = template!(NameValueStr: "ClassName");
@@ -190,7 +172,6 @@ pub(crate) struct RustcObjcSelectorParser;
impl<S: Stage> SingleAttributeParser<S> for RustcObjcSelectorParser {
const PATH: &[rustc_span::Symbol] = &[sym::rustc_objc_selector];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::ForeignStatic)]);
const TEMPLATE: AttributeTemplate = template!(NameValueStr: "methodName");
@@ -238,6 +219,7 @@ impl<S: Stage> AttributeParser<S> for NakedParser {
this.span = Some(cx.attr_span);
}
})];
const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: None };
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -358,6 +340,7 @@ pub(crate) struct NoMangleParser;
impl<S: Stage> NoArgsAttributeParser<S> for NoMangleParser {
const PATH: &[Symbol] = &[sym::no_mangle];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: Some(Edition2024) };
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowListWarnRest(&[
Allow(Target::Fn),
Allow(Target::Static),
@@ -388,8 +371,7 @@ impl<S: Stage> AttributeParser<S> for UsedParser {
let used_by = match args {
ArgParser::NoArgs => UsedBy::Default,
ArgParser::List(list) => {
let Some(l) = list.single() else {
cx.adcx().expected_single_argument(list.span);
let Some(l) = cx.expect_single(list) else {
return;
};
@@ -480,9 +462,7 @@ fn parse_tf_attribute<S: Stage>(
args: &ArgParser,
) -> impl IntoIterator<Item = (Symbol, Span)> {
let mut features = Vec::new();
let ArgParser::List(list) = args else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
let Some(list) = cx.expect_list(args, cx.attr_span) else {
return features;
};
if list.is_empty() {
@@ -560,6 +540,7 @@ pub(crate) struct ForceTargetFeatureParser;
impl<S: Stage> CombineAttributeParser<S> for ForceTargetFeatureParser {
type Item = (Symbol, Span);
const PATH: &[Symbol] = &[sym::force_target_feature];
const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: None };
const CONVERT: ConvertFn<Self::Item> = |items, span| AttributeKind::TargetFeature {
features: items,
attr_span: span,
@@ -603,14 +584,8 @@ impl<S: Stage> SingleAttributeParser<S> for SanitizeParser {
r#"realtime = "nonblocking|blocking|caller""#,
]);
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let list = cx.expect_list(args, cx.attr_span)?;
let mut on_set = SanitizerSet::empty();
let mut off_set = SanitizerSet::empty();
@@ -707,7 +682,6 @@ pub(crate) struct ThreadLocalParser;
impl<S: Stage> NoArgsAttributeParser<S> for ThreadLocalParser {
const PATH: &[Symbol] = &[sym::thread_local];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::WarnButFutureError;
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::Static), Allow(Target::ForeignStatic)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::ThreadLocal;
@@ -717,7 +691,6 @@ pub(crate) struct RustcPassIndirectlyInNonRusticAbisParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcPassIndirectlyInNonRusticAbisParser {
const PATH: &[Symbol] = &[sym::rustc_pass_indirectly_in_non_rustic_abis];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Struct)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcPassIndirectlyInNonRusticAbis;
}
@@ -726,8 +699,8 @@ pub(crate) struct RustcEiiForeignItemParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcEiiForeignItemParser {
const PATH: &[Symbol] = &[sym::rustc_eii_foreign_item];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::ForeignFn)]);
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::ForeignFn), Allow(Target::ForeignStatic)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcEiiForeignItem;
}
@@ -735,22 +708,17 @@ pub(crate) struct PatchableFunctionEntryParser;
impl<S: Stage> SingleAttributeParser<S> for PatchableFunctionEntryParser {
const PATH: &[Symbol] = &[sym::patchable_function_entry];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const TEMPLATE: AttributeTemplate = template!(List: &["prefix_nops = m, entry_nops = n"]);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(meta_item_list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let meta_item_list = cx.expect_list(args, cx.attr_span)?;
let mut prefix = None;
let mut entry = None;
if meta_item_list.len() == 0 {
cx.adcx().expected_list(meta_item_list.span, args);
cx.adcx().expected_at_least_one_argument(meta_item_list.span);
return None;
}

View File

@@ -12,11 +12,7 @@ impl<S: Stage> AttributeParser<S> for ConfusablesParser {
&[sym::rustc_confusables],
template!(List: &[r#""name1", "name2", ..."#]),
|this, cx, args| {
let Some(list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return;
};
let Some(list) = cx.expect_list(args, cx.attr_span) else { return };
if list.is_empty() {
cx.emit_err(EmptyConfusables { span: cx.attr_span });
@@ -44,9 +40,6 @@ impl<S: Stage> AttributeParser<S> for ConfusablesParser {
return None;
}
Some(AttributeKind::RustcConfusables {
symbols: self.confusables,
first_span: self.first_span.unwrap(),
})
Some(AttributeKind::RustcConfusables { confusables: self.confusables })
}
}

View File

@@ -1,10 +1,11 @@
use rustc_errors::Diagnostic;
use rustc_hir::attrs::{CrateType, WindowsSubsystemKind};
use rustc_hir::lints::AttributeLintKind;
use rustc_session::lint::builtin::UNKNOWN_CRATE_TYPES;
use rustc_span::Symbol;
use rustc_span::edit_distance::find_best_match_for_name;
use super::prelude::*;
use crate::errors::{UnknownCrateTypes, UnknownCrateTypesSuggestion};
pub(crate) struct CrateNameParser;
@@ -65,13 +66,17 @@ impl<S: Stage> CombineAttributeParser<S> for CrateTypeParser {
crate_type,
None,
);
cx.emit_lint(
let span = n.value_span;
cx.emit_dyn_lint(
UNKNOWN_CRATE_TYPES,
AttributeLintKind::CrateTypeUnknown {
span: n.value_span,
suggested: candidate,
move |dcx, level| {
UnknownCrateTypes {
sugg: candidate
.map(|s| UnknownCrateTypesSuggestion { span, snippet: s }),
}
.into_diag(dcx, level)
},
n.value_span,
span,
);
}
return None;
@@ -108,7 +113,6 @@ pub(crate) struct MoveSizeLimitParser;
impl<S: Stage> SingleAttributeParser<S> for MoveSizeLimitParser {
const PATH: &[Symbol] = &[sym::move_size_limit];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const TEMPLATE: AttributeTemplate = template!(NameValueStr: "N");
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
@@ -154,7 +158,6 @@ pub(crate) struct PatternComplexityLimitParser;
impl<S: Stage> SingleAttributeParser<S> for PatternComplexityLimitParser {
const PATH: &[Symbol] = &[sym::pattern_complexity_limit];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const TEMPLATE: AttributeTemplate = template!(NameValueStr: "N");
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
@@ -177,7 +180,6 @@ pub(crate) struct NoCoreParser;
impl<S: Stage> NoArgsAttributeParser<S> for NoCoreParser {
const PATH: &[Symbol] = &[sym::no_core];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::NoCore;
}
@@ -204,7 +206,6 @@ pub(crate) struct RustcCoherenceIsCoreParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcCoherenceIsCoreParser {
const PATH: &[Symbol] = &[sym::rustc_coherence_is_core];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcCoherenceIsCore;
}
@@ -247,7 +248,6 @@ pub(crate) struct PanicRuntimeParser;
impl<S: Stage> NoArgsAttributeParser<S> for PanicRuntimeParser {
const PATH: &[Symbol] = &[sym::panic_runtime];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::PanicRuntime;
}
@@ -256,7 +256,6 @@ pub(crate) struct NeedsPanicRuntimeParser;
impl<S: Stage> NoArgsAttributeParser<S> for NeedsPanicRuntimeParser {
const PATH: &[Symbol] = &[sym::needs_panic_runtime];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::NeedsPanicRuntime;
}
@@ -265,7 +264,6 @@ pub(crate) struct ProfilerRuntimeParser;
impl<S: Stage> NoArgsAttributeParser<S> for ProfilerRuntimeParser {
const PATH: &[Symbol] = &[sym::profiler_runtime];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::ProfilerRuntime;
}
@@ -283,7 +281,6 @@ pub(crate) struct RustcPreserveUbChecksParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcPreserveUbChecksParser {
const PATH: &[Symbol] = &[sym::rustc_preserve_ub_checks];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcPreserveUbChecks;
}
@@ -292,7 +289,6 @@ pub(crate) struct RustcNoImplicitBoundsParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcNoImplicitBoundsParser {
const PATH: &[Symbol] = &[sym::rustc_no_implicit_bounds];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcNoImplicitBounds;
}
@@ -301,7 +297,6 @@ pub(crate) struct DefaultLibAllocatorParser;
impl<S: Stage> NoArgsAttributeParser<S> for DefaultLibAllocatorParser {
const PATH: &[Symbol] = &[sym::default_lib_allocator];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::DefaultLibAllocator;
}
@@ -319,9 +314,7 @@ impl<S: Stage> CombineAttributeParser<S> for FeatureParser {
cx: &mut AcceptContext<'_, '_, S>,
args: &ArgParser,
) -> impl IntoIterator<Item = Self::Item> {
let ArgParser::List(list) = args else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
let Some(list) = cx.expect_list(args, cx.attr_span) else {
return Vec::new();
};
@@ -367,9 +360,7 @@ impl<S: Stage> CombineAttributeParser<S> for RegisterToolParser {
cx: &mut AcceptContext<'_, '_, S>,
args: &ArgParser,
) -> impl IntoIterator<Item = Self::Item> {
let ArgParser::List(list) = args else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
let Some(list) = cx.expect_list(args, cx.attr_span) else {
return Vec::new();
};

View File

@@ -20,15 +20,7 @@ impl<S: Stage> CombineAttributeParser<S> for DebuggerViualizerParser {
cx: &mut AcceptContext<'_, '_, S>,
args: &ArgParser,
) -> impl IntoIterator<Item = Self::Item> {
let Some(l) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let Some(single) = l.single() else {
cx.adcx().expected_single_argument(l.span);
return None;
};
let single = cx.expect_single_element_list(args, cx.attr_span)?;
let Some(mi) = single.meta_item() else {
cx.adcx().expected_name_value(single.span(), None);
return None;

View File

@@ -34,7 +34,6 @@ fn get<S: Stage>(
pub(crate) struct DeprecatedParser;
impl<S: Stage> SingleAttributeParser<S> for DeprecatedParser {
const PATH: &[Symbol] = &[sym::deprecated];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowListWarnRest(&[
Allow(Target::Fn),
Allow(Target::Mod),

View File

@@ -1,11 +1,15 @@
use rustc_errors::Diagnostic;
use rustc_feature::{AttributeTemplate, template};
use rustc_hir::Target;
use rustc_hir::attrs::AttributeKind;
use rustc_hir::lints::AttributeLintKind;
use rustc_session::lint::builtin::MALFORMED_DIAGNOSTIC_ATTRIBUTES;
use rustc_session::lint::builtin::{
MALFORMED_DIAGNOSTIC_ATTRIBUTES, MISPLACED_DIAGNOSTIC_ATTRIBUTES,
};
use rustc_span::{Symbol, sym};
use crate::attributes::{OnDuplicate, SingleAttributeParser};
use crate::context::{AcceptContext, Stage};
use crate::errors::IncorrectDoNotRecommendLocation;
use crate::parser::ArgParser;
use crate::target_checking::{ALL_TARGETS, AllowedTargets};
@@ -13,18 +17,32 @@ pub(crate) struct DoNotRecommendParser;
impl<S: Stage> SingleAttributeParser<S> for DoNotRecommendParser {
const PATH: &[Symbol] = &[sym::diagnostic, sym::do_not_recommend];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); // Checked in check_attr.
// "Allowed" on any target, noop on all but trait impls
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS);
const TEMPLATE: AttributeTemplate = template!(Word /*doesn't matter */);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let attr_span = cx.attr_span;
if !matches!(args, ArgParser::NoArgs) {
cx.emit_lint(
cx.emit_dyn_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::DoNotRecommendDoesNotExpectArgs,
|dcx, level| crate::errors::DoNotRecommendDoesNotExpectArgs.into_diag(dcx, level),
attr_span,
);
}
if !matches!(cx.target, Target::Impl { of_trait: true }) {
let target_span = cx.target_span;
cx.emit_dyn_lint(
MISPLACED_DIAGNOSTIC_ATTRIBUTES,
move |dcx, level| {
IncorrectDoNotRecommendLocation { target_span }.into_diag(dcx, level)
},
attr_span,
);
return None;
}
Some(AttributeKind::DoNotRecommend { attr_span })
}
}

View File

@@ -1,12 +1,11 @@
use std::ops::Range;
use rustc_errors::E0232;
use rustc_errors::{Diagnostic, E0232};
use rustc_hir::AttrPath;
use rustc_hir::attrs::diagnostic::{
Directive, FilterFormatString, Flag, FormatArg, FormatString, LitOrArg, Name, NameValue,
OnUnimplementedCondition, Piece, Predicate,
};
use rustc_hir::lints::{AttributeLintKind, FormatWarning};
use rustc_macros::Diagnostic;
use rustc_parse_format::{
Argument, FormatSpec, ParseError, ParseMode, Parser, Piece as RpfPiece, Position,
@@ -18,6 +17,10 @@ use rustc_span::{Ident, InnerSpan, Span, Symbol, kw, sym};
use thin_vec::{ThinVec, thin_vec};
use crate::context::{AcceptContext, Stage};
use crate::errors::{
FormatWarning, IgnoredDiagnosticOption, MalFormedDiagnosticAttributeLint,
MissingOptionsForDiagnosticAttribute, NonMetaItemDiagnosticAttribute, WrappedParserError,
};
use crate::parser::{ArgParser, MetaItemListParser, MetaItemOrLitParser, MetaItemParser};
pub(crate) mod do_not_recommend;
@@ -25,6 +28,7 @@ pub(crate) mod on_const;
pub(crate) mod on_move;
pub(crate) mod on_unimplemented;
pub(crate) mod on_unknown;
pub(crate) mod on_unmatch_args;
#[derive(Copy, Clone)]
pub(crate) enum Mode {
@@ -38,6 +42,73 @@ pub(crate) enum Mode {
DiagnosticOnMove,
/// `#[diagnostic::on_unknown]`
DiagnosticOnUnknown,
/// `#[diagnostic::on_unmatch_args]`
DiagnosticOnUnmatchArgs,
}
impl Mode {
fn as_str(&self) -> &'static str {
match self {
Self::RustcOnUnimplemented => "rustc_on_unimplemented",
Self::DiagnosticOnUnimplemented => "diagnostic::on_unimplemented",
Self::DiagnosticOnConst => "diagnostic::on_const",
Self::DiagnosticOnMove => "diagnostic::on_move",
Self::DiagnosticOnUnknown => "diagnostic::on_unknown",
Self::DiagnosticOnUnmatchArgs => "diagnostic::on_unmatch_args",
}
}
fn expected_options(&self) -> &'static str {
const DEFAULT: &str =
"at least one of the `message`, `note` and `label` options are expected";
match self {
Self::RustcOnUnimplemented => {
"see <https://rustc-dev-guide.rust-lang.org/diagnostics.html#rustc_on_unimplemented>"
}
Self::DiagnosticOnUnimplemented => DEFAULT,
Self::DiagnosticOnConst => DEFAULT,
Self::DiagnosticOnMove => DEFAULT,
Self::DiagnosticOnUnknown => DEFAULT,
Self::DiagnosticOnUnmatchArgs => DEFAULT,
}
}
fn allowed_options(&self) -> &'static str {
const DEFAULT: &str = "only `message`, `note` and `label` are allowed as options";
match self {
Self::RustcOnUnimplemented => {
"see <https://rustc-dev-guide.rust-lang.org/diagnostics.html#rustc_on_unimplemented>"
}
Self::DiagnosticOnUnimplemented => DEFAULT,
Self::DiagnosticOnConst => DEFAULT,
Self::DiagnosticOnMove => DEFAULT,
Self::DiagnosticOnUnknown => DEFAULT,
Self::DiagnosticOnUnmatchArgs => DEFAULT,
}
}
fn allowed_format_arguments(&self) -> &'static str {
match self {
Self::RustcOnUnimplemented => {
"see <https://rustc-dev-guide.rust-lang.org/diagnostics.html#rustc_on_unimplemented> for allowed format arguments"
}
Self::DiagnosticOnUnimplemented => {
"only `Self` and generics of the trait are allowed as a format argument"
}
Self::DiagnosticOnConst => {
"only `Self` and generics of the implementation are allowed as a format argument"
}
Self::DiagnosticOnMove => {
"only `This`, `Self` and generics of the type are allowed as a format argument"
}
Self::DiagnosticOnUnknown => {
"only `This` is allowed as a format argument, referring to the failed import"
}
Self::DiagnosticOnUnmatchArgs => {
"only `This` is allowed as a format argument, referring to the macro's name"
}
}
}
}
fn merge_directives<S: Stage>(
@@ -67,12 +138,12 @@ fn merge<T, S: Stage>(
match (first, later) {
(Some(_) | None, None) => {}
(Some((first_span, _)), Some((later_span, _))) => {
cx.emit_lint(
let first_span = *first_span;
cx.emit_dyn_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::IgnoredDiagnosticOption {
first_span: *first_span,
later_span,
option_name,
move |dcx, level| {
IgnoredDiagnosticOption { first_span, later_span, option_name }
.into_diag(dcx, level)
},
later_span,
);
@@ -83,6 +154,55 @@ fn merge<T, S: Stage>(
}
}
fn parse_list<'p, S: Stage>(
cx: &mut AcceptContext<'_, '_, S>,
args: &'p ArgParser,
mode: Mode,
) -> Option<&'p MetaItemListParser> {
let span = cx.attr_span;
match args {
ArgParser::List(items) if items.len() != 0 => return Some(items),
ArgParser::List(list) => {
// We're dealing with `#[diagnostic::attr()]`.
// This can be because that is what the user typed, but that's also what we'd see
// if the user used non-metaitem syntax. See `ArgParser::from_attr_args`.
cx.emit_dyn_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
move |dcx, level| NonMetaItemDiagnosticAttribute.into_diag(dcx, level),
list.span,
);
}
ArgParser::NoArgs => {
cx.emit_dyn_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
move |dcx, level| {
MissingOptionsForDiagnosticAttribute {
attribute: mode.as_str(),
options: mode.expected_options(),
}
.into_diag(dcx, level)
},
span,
);
}
ArgParser::NameValue(_) => {
cx.emit_dyn_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
move |dcx, level| {
MalFormedDiagnosticAttributeLint {
attribute: mode.as_str(),
options: mode.allowed_options(),
span,
}
.into_diag(dcx, level)
},
span,
);
}
}
None
}
fn parse_directive_items<'p, S: Stage>(
cx: &mut AcceptContext<'_, '_, S>,
mode: Mode,
@@ -100,68 +220,43 @@ fn parse_directive_items<'p, S: Stage>(
let span = item.span();
macro malformed() {{
match mode {
Mode::RustcOnUnimplemented => {
cx.emit_err(NoValueInOnUnimplemented { span: item.span() });
}
Mode::DiagnosticOnUnimplemented => {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::MalformedOnUnimplementedAttr { span },
cx.emit_dyn_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
move |dcx, level| {
MalFormedDiagnosticAttributeLint {
attribute: mode.as_str(),
options: mode.allowed_options(),
span,
);
}
Mode::DiagnosticOnConst => {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::MalformedOnConstAttr { span },
span,
);
}
Mode::DiagnosticOnMove => {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::MalformedOnMoveAttr { span },
span,
);
}
Mode::DiagnosticOnUnknown => {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::MalformedOnUnknownAttr { span },
span,
);
}
}
}
.into_diag(dcx, level)
},
span,
);
continue;
}}
macro or_malformed($($code:tt)*) {{
let Some(ret) = (||{
Some($($code)*)
})() else {
let Some(ret) = (
try {
$($code)*
}
) else {
malformed!()
};
ret
}}
macro duplicate($name: ident, $($first_span:tt)*) {{
match mode {
Mode::RustcOnUnimplemented => {
cx.emit_err(NoValueInOnUnimplemented { span: item.span() });
}
Mode::DiagnosticOnUnimplemented |Mode::DiagnosticOnConst | Mode::DiagnosticOnMove | Mode::DiagnosticOnUnknown => {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::IgnoredDiagnosticOption {
first_span: $($first_span)*,
later_span: span,
option_name: $name,
},
span,
);
}
}
let first_span = $($first_span)*;
cx.emit_dyn_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
move |dcx, level| IgnoredDiagnosticOption {
first_span,
later_span: span,
option_name: $name,
}.into_diag(dcx, level),
span,
);
}}
let item: &MetaItemParser = or_malformed!(item.meta_item()?);
@@ -185,12 +280,13 @@ fn parse_directive_items<'p, S: Stage>(
match parse_format_string(input.name, snippet, input.span, mode) {
Ok((f, warnings)) => {
for warning in warnings {
let (FormatWarning::InvalidSpecifier { span, .. }
| FormatWarning::PositionalArgument { span, .. }
| FormatWarning::DisallowedPlaceholder { span }) = warning;
cx.emit_lint(
let (FormatWarning::InvalidSpecifier { span }
| FormatWarning::PositionalArgument { span }
| FormatWarning::IndexedArgument { span }
| FormatWarning::DisallowedPlaceholder { span, .. }) = warning;
cx.emit_dyn_lint(
MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
AttributeLintKind::MalformedDiagnosticFormat { warning },
move |dcx, level| warning.into_diag(dcx, level),
span,
);
}
@@ -198,12 +294,15 @@ fn parse_directive_items<'p, S: Stage>(
f
}
Err(e) => {
cx.emit_lint(
cx.emit_dyn_lint(
MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
AttributeLintKind::DiagnosticWrappedParserError {
description: e.description,
label: e.label,
span: slice_span(input.span, e.span, is_snippet),
move |dcx, level| {
WrappedParserError {
description: &e.description,
label: &e.label,
span: slice_span(input.span, e.span.clone(), is_snippet),
}
.into_diag(dcx, level)
},
input.span,
);
@@ -247,7 +346,7 @@ fn parse_directive_items<'p, S: Stage>(
}
(Mode::RustcOnUnimplemented, sym::on) => {
if is_root {
let items = or_malformed!(item.args().list()?);
let items = or_malformed!(item.args().as_list()?);
let mut iter = items.mixed();
let condition: &MetaItemOrLitParser = match iter.next() {
Some(c) => c,
@@ -337,36 +436,74 @@ fn parse_arg(
is_source_literal: bool,
) -> FormatArg {
let span = slice_span(input_span, arg.position_span.clone(), is_source_literal);
if matches!(mode, Mode::DiagnosticOnUnknown) {
warnings.push(FormatWarning::DisallowedPlaceholder { span });
return FormatArg::AsIs(sym::empty_braces);
}
match arg.position {
// Something like "hello {name}"
Position::ArgumentNamed(name) => match (mode, Symbol::intern(name)) {
// Only `#[rustc_on_unimplemented]` can use these
(Mode::RustcOnUnimplemented { .. }, sym::ItemContext) => FormatArg::ItemContext,
(Mode::RustcOnUnimplemented { .. }, sym::This) => FormatArg::This,
(Mode::RustcOnUnimplemented { .. }, sym::Trait) => FormatArg::Trait,
// Any attribute can use these
(_, kw::SelfUpper) => FormatArg::SelfUpper,
(_, generic_param) => FormatArg::GenericParam { generic_param, span },
(Mode::RustcOnUnimplemented, sym::ItemContext) => FormatArg::ItemContext,
// Like `{This}`, but sugared.
// FIXME(mejrs) maybe rename/rework this or something
// if we want to apply this to other attrs?
(Mode::RustcOnUnimplemented, sym::Trait) => FormatArg::Trait,
// Some diagnostic attributes can use `{This}` to refer to the annotated item.
// For those that don't, we continue and maybe use it as a generic parameter.
//
// FIXME(mejrs) `DiagnosticOnUnimplemented` is intentionally not here;
// that requires lang approval which is best kept for a standalone PR.
(
Mode::RustcOnUnimplemented
| Mode::DiagnosticOnUnknown
| Mode::DiagnosticOnMove
| Mode::DiagnosticOnUnmatchArgs,
sym::This,
) => FormatArg::This,
// `{Self}`; the self type.
// - For trait declaration attributes that's the type that does not implement it.
// - for trait impl attributes, the implemented for type.
// - For ADT attributes, that's the type (which will be identical to `{This}`)
// - For everything else it doesn't make sense.
(
Mode::RustcOnUnimplemented
| Mode::DiagnosticOnUnimplemented
| Mode::DiagnosticOnMove
| Mode::DiagnosticOnConst,
kw::SelfUpper,
) => FormatArg::SelfUpper,
// Generic parameters.
// FIXME(mejrs) unfortunately, all the "special" symbols above might fall through,
// but at this time we are not aware of what generic parameters the trait actually has.
// If we find `ItemContext` or something we have to assume that's a generic parameter.
// We lint against that in `check_attr.rs` though.
(
Mode::RustcOnUnimplemented
| Mode::DiagnosticOnUnimplemented
| Mode::DiagnosticOnMove
| Mode::DiagnosticOnConst,
generic_param,
) => FormatArg::GenericParam { generic_param, span },
// Generics are explicitly not allowed, we print those back as is.
(Mode::DiagnosticOnUnknown | Mode::DiagnosticOnUnmatchArgs, as_is) => {
warnings.push(FormatWarning::DisallowedPlaceholder {
span,
attr: mode.as_str(),
allowed: mode.allowed_format_arguments(),
});
return FormatArg::AsIs(Symbol::intern(&format!("{{{as_is}}}")));
}
},
// `{:1}` and `{}` are ignored
Position::ArgumentIs(idx) => {
warnings.push(FormatWarning::PositionalArgument {
span,
help: format!("use `{{{idx}}}` to print a number in braces"),
});
warnings.push(FormatWarning::IndexedArgument { span });
FormatArg::AsIs(Symbol::intern(&format!("{{{idx}}}")))
}
Position::ArgumentImplicitlyIs(_) => {
warnings.push(FormatWarning::PositionalArgument {
span,
help: String::from("use `{{}}` to print empty braces"),
});
warnings.push(FormatWarning::PositionalArgument { span });
FormatArg::AsIs(sym::empty_braces)
}
}
@@ -386,7 +523,7 @@ fn warn_on_format_spec(
.as_ref()
.map(|inner| slice_span(input_span, inner.clone(), is_source_literal))
.unwrap_or(input_span);
warnings.push(FormatWarning::InvalidSpecifier { span, name: spec.ty.into() })
warnings.push(FormatWarning::InvalidSpecifier { span })
}
}
@@ -419,7 +556,7 @@ fn parse_predicate(input: &MetaItemOrLitParser) -> Result<Predicate, InvalidOnCl
sym::any => Ok(Predicate::Any(parse_predicate_sequence(mis)?)),
sym::all => Ok(Predicate::All(parse_predicate_sequence(mis)?)),
sym::not => {
if let Some(single) = mis.single() {
if let Some(single) = mis.as_single() {
Ok(Predicate::Not(Box::new(parse_predicate(single)?)))
} else {
Err(InvalidOnClause::ExpectedOnePredInNot { span: mis.span })
@@ -540,15 +677,6 @@ pub(crate) enum InvalidOnClause {
},
}
#[derive(Diagnostic)]
#[diag("this attribute must have a value", code = E0232)]
#[note("e.g. `#[rustc_on_unimplemented(message=\"foo\")]`")]
pub(crate) struct NoValueInOnUnimplemented {
#[primary_span]
#[label("expected value here")]
pub span: Span,
}
#[derive(Diagnostic)]
#[diag(
"using multiple `rustc_on_unimplemented` (or mixing it with `diagnostic::on_unimplemented`) is not supported"

View File

@@ -1,10 +1,10 @@
use rustc_errors::Diagnostic;
use rustc_hir::attrs::diagnostic::Directive;
use rustc_hir::lints::AttributeLintKind;
use rustc_session::lint::builtin::MALFORMED_DIAGNOSTIC_ATTRIBUTES;
use rustc_session::lint::builtin::MISPLACED_DIAGNOSTIC_ATTRIBUTES;
use crate::attributes::diagnostic::*;
use crate::attributes::prelude::*;
use crate::errors::DiagnosticOnConstOnlyForTraitImpls;
#[derive(Default)]
pub(crate) struct OnConstParser {
span: Option<Span>,
@@ -17,42 +17,40 @@ impl<S: Stage> AttributeParser<S> for OnConstParser {
template!(List: &[r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#]),
|this, cx, args| {
if !cx.features().diagnostic_on_const() {
// `UnknownDiagnosticAttribute` is emitted in rustc_resolve/macros.rs
return;
}
let span = cx.attr_span;
this.span = Some(span);
let items = match args {
ArgParser::List(items) if items.len() != 0 => items,
ArgParser::NoArgs | ArgParser::List(_) => {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::MissingOptionsForOnConst,
span,
);
return;
}
ArgParser::NameValue(_) => {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::MalformedOnConstAttr { span },
span,
);
return;
}
};
// FIXME(mejrs) no constness field on `Target`,
// so non-constness is still checked in check_attr.rs
if !matches!(cx.target, Target::Impl { of_trait: true }) {
let target_span = cx.target_span;
cx.emit_dyn_lint(
MISPLACED_DIAGNOSTIC_ATTRIBUTES,
move |dcx, level| {
DiagnosticOnConstOnlyForTraitImpls { target_span }.into_diag(dcx, level)
},
span,
);
return;
}
let Some(directive) =
parse_directive_items(cx, Mode::DiagnosticOnConst, items.mixed(), true)
else {
let mode = Mode::DiagnosticOnConst;
let Some(items) = parse_list(cx, args, mode) else { return };
let Some(directive) = parse_directive_items(cx, mode, items.mixed(), true) else {
return;
};
merge_directives(cx, &mut this.directive, (span, directive));
},
)];
//FIXME Still checked in `check_attr.rs`
// "Allowed" on all targets; noop on anything but non-const trait impls;
// this linted on in parser.
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS);
fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {

View File

@@ -1,12 +1,13 @@
use rustc_errors::Diagnostic;
use rustc_feature::template;
use rustc_hir::attrs::AttributeKind;
use rustc_hir::lints::AttributeLintKind;
use rustc_session::lint::builtin::MALFORMED_DIAGNOSTIC_ATTRIBUTES;
use rustc_session::lint::builtin::MISPLACED_DIAGNOSTIC_ATTRIBUTES;
use rustc_span::sym;
use crate::attributes::diagnostic::*;
use crate::attributes::prelude::*;
use crate::context::{AcceptContext, Stage};
use crate::errors::DiagnosticOnMoveOnlyForAdt;
use crate::parser::ArgParser;
use crate::target_checking::{ALL_TARGETS, AllowedTargets};
@@ -24,30 +25,25 @@ impl OnMoveParser {
mode: Mode,
) {
if !cx.features().diagnostic_on_move() {
// `UnknownDiagnosticAttribute` is emitted in rustc_resolve/macros.rs
return;
}
let span = cx.attr_span;
self.span = Some(span);
let Some(list) = args.list() else {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::MissingOptionsForOnMove,
span,
);
return;
};
if list.is_empty() {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::OnMoveMalformedAttrExpectedLiteralOrDelimiter,
list.span,
if !matches!(cx.target, Target::Enum | Target::Struct | Target::Union) {
cx.emit_dyn_lint(
MISPLACED_DIAGNOSTIC_ATTRIBUTES,
move |dcx, level| DiagnosticOnMoveOnlyForAdt.into_diag(dcx, level),
span,
);
return;
}
if let Some(directive) = parse_directive_items(cx, mode, list.mixed(), true) {
let Some(items) = parse_list(cx, args, mode) else { return };
if let Some(directive) = parse_directive_items(cx, mode, items.mixed(), true) {
merge_directives(cx, &mut self.directive, (span, directive));
}
}
@@ -60,6 +56,8 @@ impl<S: Stage> AttributeParser<S> for OnMoveParser {
this.parse(cx, args, Mode::DiagnosticOnMove);
},
)];
// "Allowed" for all targets but noop if used on not-adt.
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS);
fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {

View File

@@ -1,9 +1,10 @@
use rustc_errors::Diagnostic;
use rustc_hir::attrs::diagnostic::Directive;
use rustc_hir::lints::AttributeLintKind;
use rustc_session::lint::builtin::MALFORMED_DIAGNOSTIC_ATTRIBUTES;
use rustc_session::lint::builtin::MISPLACED_DIAGNOSTIC_ATTRIBUTES;
use crate::attributes::diagnostic::*;
use crate::attributes::prelude::*;
use crate::errors::DiagnosticOnUnimplementedOnlyForTraits;
#[derive(Default)]
pub(crate) struct OnUnimplementedParser {
@@ -21,33 +22,16 @@ impl OnUnimplementedParser {
let span = cx.attr_span;
self.span = Some(span);
// If target is not a trait, returning early will make `finalize` emit a
// `AttributeKind::OnUnimplemented {span, directive: None }`, to prevent it being
// accidentally used on non-trait items like trait aliases.
if !matches!(cx.target, Target::Trait) {
// Lint later emitted in check_attr
cx.emit_dyn_lint(
MISPLACED_DIAGNOSTIC_ATTRIBUTES,
move |dcx, level| DiagnosticOnUnimplementedOnlyForTraits.into_diag(dcx, level),
span,
);
return;
}
let items = match args {
ArgParser::List(items) if items.len() != 0 => items,
ArgParser::NoArgs | ArgParser::List(_) => {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::MissingOptionsForOnUnimplemented,
span,
);
return;
}
ArgParser::NameValue(_) => {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::MalformedOnUnimplementedAttr { span },
span,
);
return;
}
};
let Some(items) = parse_list(cx, args, mode) else { return };
if let Some(directive) = parse_directive_items(cx, mode, items.mixed(), true) {
merge_directives(cx, &mut self.directive, (span, directive));

View File

@@ -1,8 +1,11 @@
use rustc_errors::Diagnostic;
use rustc_hir::attrs::diagnostic::Directive;
use rustc_session::lint::builtin::MALFORMED_DIAGNOSTIC_ATTRIBUTES;
use rustc_session::lint::builtin::MISPLACED_DIAGNOSTIC_ATTRIBUTES;
use crate::ShouldEmit;
use crate::attributes::diagnostic::*;
use crate::attributes::prelude::*;
use crate::errors::DiagnosticOnUnknownOnlyForImports;
#[derive(Default)]
pub(crate) struct OnUnknownParser {
@@ -17,31 +20,32 @@ impl OnUnknownParser {
args: &ArgParser,
mode: Mode,
) {
if !cx.features().diagnostic_on_unknown() {
if let Some(features) = cx.features
&& !features.diagnostic_on_unknown()
{
// `UnknownDiagnosticAttribute` is emitted in rustc_resolve/macros.rs
return;
}
let span = cx.attr_span;
self.span = Some(span);
let items = match args {
ArgParser::List(items) if !items.is_empty() => items,
ArgParser::NoArgs | ArgParser::List(_) => {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::MissingOptionsForOnUnknown,
span,
);
return;
}
ArgParser::NameValue(_) => {
cx.emit_lint(
MALFORMED_DIAGNOSTIC_ATTRIBUTES,
AttributeLintKind::MalformedOnUnknownAttr { span },
span,
);
return;
}
};
// At early parsing we get passed `Target::Crate` regardless of the item we're on.
// Only do target checking if we're late.
let early = matches!(cx.stage.should_emit(), ShouldEmit::Nothing);
if !early && !matches!(cx.target, Target::Use) {
let target_span = cx.target_span;
cx.emit_dyn_lint(
MISPLACED_DIAGNOSTIC_ATTRIBUTES,
move |dcx, level| {
DiagnosticOnUnknownOnlyForImports { target_span }.into_diag(dcx, level)
},
span,
);
return;
}
let Some(items) = parse_list(cx, args, mode) else { return };
if let Some(directive) = parse_directive_items(cx, mode, items.mixed(), true) {
merge_directives(cx, &mut self.directive, (span, directive));
@@ -57,7 +61,7 @@ impl<S: Stage> AttributeParser<S> for OnUnknownParser {
this.parse(cx, args, Mode::DiagnosticOnUnknown);
},
)];
//FIXME attribute is not parsed for non-use statements but diagnostics are issued in `check_attr.rs`
// "Allowed" for all targets, but noop for all but use statements.
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS);
fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {

View File

@@ -0,0 +1,58 @@
use rustc_errors::Diagnostic;
use rustc_hir::attrs::diagnostic::Directive;
use rustc_session::lint::builtin::MISPLACED_DIAGNOSTIC_ATTRIBUTES;
use crate::attributes::diagnostic::*;
use crate::attributes::prelude::*;
use crate::errors::DiagnosticOnUnmatchArgsOnlyForMacros;
#[derive(Default)]
pub(crate) struct OnUnmatchArgsParser {
span: Option<Span>,
directive: Option<(Span, Directive)>,
}
impl<S: Stage> AttributeParser<S> for OnUnmatchArgsParser {
const ATTRIBUTES: AcceptMapping<Self, S> = &[(
&[sym::diagnostic, sym::on_unmatch_args],
template!(List: &[r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#]),
|this, cx, args| {
if !cx.features().diagnostic_on_unmatch_args() {
return;
}
let span = cx.attr_span;
this.span = Some(span);
if !matches!(cx.target, Target::MacroDef) {
cx.emit_dyn_lint(
MISPLACED_DIAGNOSTIC_ATTRIBUTES,
move |dcx, level| DiagnosticOnUnmatchArgsOnlyForMacros.into_diag(dcx, level),
span,
);
return;
}
let mode = Mode::DiagnosticOnUnmatchArgs;
let Some(items) = parse_list(cx, args, mode) else { return };
let Some(directive) = parse_directive_items(cx, mode, items.mixed(), true) else {
return;
};
merge_directives(cx, &mut this.directive, (span, directive));
},
)];
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS);
fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
if let Some(span) = self.span {
Some(AttributeKind::OnUnmatchArgs {
span,
directive: self.directive.map(|d| Box::new(d.1)),
})
} else {
None
}
}
}

View File

@@ -1,11 +1,10 @@
use rustc_ast::ast::{AttrStyle, LitKind, MetaItemLit};
use rustc_errors::msg;
use rustc_errors::{Applicability, Diagnostic, msg};
use rustc_feature::template;
use rustc_hir::Target;
use rustc_hir::attrs::{
AttributeKind, CfgEntry, CfgHideShow, CfgInfo, DocAttribute, DocInline, HideOrShow,
};
use rustc_hir::lints::AttributeLintKind;
use rustc_session::parse::feature_err;
use rustc_span::{Span, Symbol, edition, sym};
use thin_vec::ThinVec;
@@ -13,6 +12,13 @@ use thin_vec::ThinVec;
use super::prelude::{ALL_TARGETS, AllowedTargets};
use super::{AcceptMapping, AttributeParser};
use crate::context::{AcceptContext, FinalizeContext, Stage};
use crate::errors::{
AttrCrateLevelOnly, DocAliasDuplicated, DocAutoCfgExpectsHideOrShow,
DocAutoCfgHideShowExpectsList, DocAutoCfgHideShowUnexpectedItem, DocAutoCfgWrongLiteral,
DocTestLiteral, DocTestTakesList, DocTestUnknown, DocUnknownAny, DocUnknownInclude,
DocUnknownPasses, DocUnknownPlugins, DocUnknownSpotlight, ExpectedNameValue, ExpectedNoArgs,
IllFormedAttributeInput, MalformedDoc,
};
use crate::parser::{ArgParser, MetaItemOrLitParser, MetaItemParser, OwnedPathParser};
use crate::session_diagnostics::{
DocAliasBadChar, DocAliasEmpty, DocAliasMalformed, DocAliasStartEnd, DocAttrNotCrateLevel,
@@ -62,9 +68,9 @@ fn check_attr_not_crate_level<S: Stage>(
/// Checks that an attribute is used at the crate level. Returns `true` if valid.
fn check_attr_crate_level<S: Stage>(cx: &mut AcceptContext<'_, '_, S>, span: Span) -> bool {
if cx.shared.target != Target::Crate {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::AttrCrateLevelOnly,
|dcx, level| AttrCrateLevelOnly.into_diag(dcx, level),
span,
);
return false;
@@ -78,18 +84,18 @@ fn expected_name_value<S: Stage>(
span: Span,
_name: Option<Symbol>,
) {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::ExpectedNameValue,
|dcx, level| ExpectedNameValue.into_diag(dcx, level),
span,
);
}
// FIXME: remove this method once merged and use `cx.expected_no_args(span)` instead.
fn expected_no_args<S: Stage>(cx: &mut AcceptContext<'_, '_, S>, span: Span) {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::ExpectedNoArgs,
|dcx, level| ExpectedNoArgs.into_diag(dcx, level),
span,
);
}
@@ -101,9 +107,9 @@ fn expected_string_literal<S: Stage>(
span: Span,
_actual_literal: Option<&MetaItemLit>,
) {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::MalformedDoc,
|dcx, level| MalformedDoc.into_diag(dcx, level),
span,
);
}
@@ -171,12 +177,15 @@ impl DocParser {
if let Some(used_span) = self.attribute.no_crate_inject {
let unused_span = path.span();
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::UnusedDuplicate {
this: unused_span,
other: used_span,
warning: true,
move |dcx, level| {
rustc_errors::lints::UnusedDuplicate {
this: unused_span,
other: used_span,
warning: true,
}
.into_diag(dcx, level)
},
unused_span,
);
@@ -190,13 +199,13 @@ impl DocParser {
self.attribute.no_crate_inject = Some(path.span())
}
Some(sym::attr) => {
let Some(list) = args.list() else {
let Some(list) = args.as_list() else {
// FIXME: remove this method once merged and uncomment the line below instead.
// cx.expected_list(cx.attr_span, args);
let span = cx.attr_span;
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::MalformedDoc,
|dcx, level| MalformedDoc.into_diag(dcx, level),
span,
);
return;
@@ -208,16 +217,16 @@ impl DocParser {
}
}
Some(name) => {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocTestUnknown { name },
move |dcx, level| DocTestUnknown { name }.into_diag(dcx, level),
path.span(),
);
}
None => {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocTestLiteral,
|dcx, level| DocTestLiteral.into_diag(dcx, level),
path.span(),
);
}
@@ -252,9 +261,9 @@ impl DocParser {
}
if let Some(first_definition) = self.attribute.aliases.get(&alias).copied() {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::UNUSED_ATTRIBUTES,
AttributeLintKind::DuplicateDocAlias { first_definition },
move |dcx, level| DocAliasDuplicated { first_definition }.into_diag(dcx, level),
span,
);
}
@@ -340,9 +349,9 @@ impl DocParser {
ArgParser::List(list) => {
for meta in list.mixed() {
let MetaItemOrLitParser::MetaItemParser(item) = meta else {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocAutoCfgExpectsHideOrShow,
|dcx, level| DocAutoCfgExpectsHideOrShow.into_diag(dcx, level),
meta.span(),
);
continue;
@@ -351,18 +360,20 @@ impl DocParser {
Some(sym::hide) => (HideOrShow::Hide, sym::hide),
Some(sym::show) => (HideOrShow::Show, sym::show),
_ => {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocAutoCfgExpectsHideOrShow,
|dcx, level| DocAutoCfgExpectsHideOrShow.into_diag(dcx, level),
item.span(),
);
continue;
}
};
let ArgParser::List(list) = item.args() else {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocAutoCfgHideShowExpectsList { attr_name },
move |dcx, level| {
DocAutoCfgHideShowExpectsList { attr_name }.into_diag(dcx, level)
},
item.span(),
);
continue;
@@ -372,9 +383,12 @@ impl DocParser {
for item in list.mixed() {
let MetaItemOrLitParser::MetaItemParser(sub_item) = item else {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocAutoCfgHideShowUnexpectedItem { attr_name },
move |dcx, level| {
DocAutoCfgHideShowUnexpectedItem { attr_name }
.into_diag(dcx, level)
},
item.span(),
);
continue;
@@ -385,9 +399,9 @@ impl DocParser {
// FIXME: remove this method once merged and uncomment the line
// below instead.
// cx.expected_identifier(sub_item.path().span());
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::MalformedDoc,
|dcx, level| MalformedDoc.into_diag(dcx, level),
sub_item.path().span(),
);
continue;
@@ -412,10 +426,11 @@ impl DocParser {
}
}
_ => {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocAutoCfgHideShowUnexpectedItem {
attr_name,
move |dcx, level| {
DocAutoCfgHideShowUnexpectedItem { attr_name }
.into_diag(dcx, level)
},
sub_item.span(),
);
@@ -429,9 +444,9 @@ impl DocParser {
ArgParser::NameValue(nv) => {
let MetaItemLit { kind: LitKind::Bool(bool_value), span, .. } = nv.value_as_lit()
else {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocAutoCfgWrongLiteral,
move |dcx, level| DocAutoCfgWrongLiteral.into_diag(dcx, level),
nv.value_span,
);
return;
@@ -572,10 +587,10 @@ impl DocParser {
}),
Some(sym::auto_cfg) => self.parse_auto_cfg(cx, path, args),
Some(sym::test) => {
let Some(list) = args.list() else {
cx.emit_lint(
let Some(list) = args.as_list() else {
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocTestTakesList,
|dcx, level| DocTestTakesList.into_diag(dcx, level),
args.span().unwrap_or(path.span()),
);
return;
@@ -590,9 +605,9 @@ impl DocParser {
// FIXME: remove this method once merged and uncomment the line
// below instead.
// cx.unexpected_literal(lit.span);
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::MalformedDoc,
|dcx, level| MalformedDoc.into_diag(dcx, level),
lit.span,
);
}
@@ -600,10 +615,11 @@ impl DocParser {
}
}
Some(sym::spotlight) => {
cx.emit_lint(
let span = path.span();
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocUnknownSpotlight { span: path.span() },
path.span(),
move |dcx, level| DocUnknownSpotlight { sugg_span: span }.into_diag(dcx, level),
span,
);
}
Some(sym::include) if let Some(nv) = args.name_value() => {
@@ -611,43 +627,53 @@ impl DocParser {
AttrStyle::Outer => "",
AttrStyle::Inner => "!",
};
cx.emit_lint(
let value = nv.value_as_lit().symbol;
let span = path.span();
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocUnknownInclude {
inner,
value: nv.value_as_lit().symbol,
span: path.span(),
move |dcx, level| {
DocUnknownInclude {
inner,
value,
sugg: (span, Applicability::MaybeIncorrect),
}
.into_diag(dcx, level)
},
path.span(),
span,
);
}
Some(name @ (sym::passes | sym::no_default_passes)) => {
cx.emit_lint(
let span = path.span();
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocUnknownPasses { name, span: path.span() },
path.span(),
move |dcx, level| {
DocUnknownPasses { name, note_span: span }.into_diag(dcx, level)
},
span,
);
}
Some(sym::plugins) => {
cx.emit_lint(
let span = path.span();
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocUnknownPlugins { span: path.span() },
path.span(),
move |dcx, level| DocUnknownPlugins { label_span: span }.into_diag(dcx, level),
span,
);
}
Some(name) => {
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocUnknownAny { name },
move |dcx, level| DocUnknownAny { name }.into_diag(dcx, level),
path.span(),
);
}
None => {
let full_name =
path.segments().map(|s| s.as_str()).intersperse("::").collect::<String>();
cx.emit_lint(
let name = Symbol::intern(&full_name);
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::DocUnknownAny { name: Symbol::intern(&full_name) },
move |dcx, level| DocUnknownAny { name }.into_diag(dcx, level),
path.span(),
);
}
@@ -663,12 +689,10 @@ impl DocParser {
ArgParser::NoArgs => {
let suggestions = cx.adcx().suggestions();
let span = cx.attr_span;
cx.emit_lint(
cx.emit_dyn_lint(
rustc_session::lint::builtin::INVALID_DOC_ATTRIBUTES,
AttributeLintKind::IllFormedAttributeInput {
suggestions,
docs: None,
help: None,
move |dcx, level| {
IllFormedAttributeInput::new(&suggestions, None, None).into_diag(dcx, level)
},
span,
);

View File

@@ -37,10 +37,7 @@ impl<S: Stage> SingleAttributeParser<S> for InlineParser {
match args {
ArgParser::NoArgs => Some(AttributeKind::Inline(InlineAttr::Hint, cx.attr_span)),
ArgParser::List(list) => {
let Some(l) = list.single() else {
cx.adcx().expected_single_argument(list.span);
return None;
};
let l = cx.expect_single(list)?;
match l.meta_item().and_then(|i| i.path().word_sym()) {
Some(sym::always) => {
@@ -67,7 +64,6 @@ pub(crate) struct RustcForceInlineParser;
impl<S: Stage> SingleAttributeParser<S> for RustcForceInlineParser {
const PATH: &[Symbol] = &[sym::rustc_force_inline];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::WarnButFutureError;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -79,10 +75,7 @@ impl<S: Stage> SingleAttributeParser<S> for RustcForceInlineParser {
let reason = match args {
ArgParser::NoArgs => None,
ArgParser::List(list) => {
let Some(l) = list.single() else {
cx.adcx().expected_single_argument(list.span);
return None;
};
let l = cx.expect_single(list)?;
let Some(reason) = l.lit().and_then(|i| i.kind.str()) else {
cx.adcx().expected_string_literal(l.span(), l.lit());

View File

@@ -15,16 +15,11 @@ impl<S: Stage> SingleAttributeParser<S> for InstructionSetParser {
Allow(Target::Method(MethodKind::Trait { body: true })),
]);
const TEMPLATE: AttributeTemplate = template!(List: &["set"], "https://doc.rust-lang.org/reference/attributes/codegen.html#the-instruction_set-attribute");
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
const POSSIBLE_SYMBOLS: &[Symbol] = &[sym::arm_a32, sym::arm_t32];
const POSSIBLE_ARM_SYMBOLS: &[Symbol] = &[sym::a32, sym::t32];
let Some(maybe_meta_item) = args.list().and_then(MetaItemListParser::single) else {
let attr_span = cx.attr_span;
cx.adcx().expected_specific_argument(attr_span, POSSIBLE_SYMBOLS);
return None;
};
let maybe_meta_item = cx.expect_single_element_list(args, cx.attr_span)?;
let Some(meta_item) = maybe_meta_item.meta_item() else {
cx.adcx().expected_specific_argument(maybe_meta_item.span(), POSSIBLE_SYMBOLS);

View File

@@ -5,17 +5,20 @@ use rustc_hir::attrs::*;
use rustc_session::Session;
use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT;
use rustc_session::parse::feature_err;
use rustc_span::edition::Edition::Edition2024;
use rustc_span::kw;
use rustc_target::spec::{Arch, BinaryFormat};
use super::prelude::*;
use super::util::parse_single_integer;
use crate::attributes::AttributeSafety;
use crate::attributes::cfg::parse_cfg_entry;
use crate::session_diagnostics::{
AsNeededCompatibility, BundleNeedsStatic, EmptyLinkName, ExportSymbolsNeedsStatic,
ImportNameTypeRaw, ImportNameTypeX86, IncompatibleWasmLink, InvalidLinkModifier,
LinkFrameworkApple, LinkOrdinalOutOfRange, LinkRequiresName, MultipleModifiers,
NullOnLinkSection, RawDylibNoNul, RawDylibOnlyWindows, WholeArchiveNeedsStatic,
InvalidMachoSection, InvalidMachoSectionReason, LinkFrameworkApple, LinkOrdinalOutOfRange,
LinkRequiresName, MultipleModifiers, NullOnLinkSection, RawDylibNoNul, RawDylibOnlyWindows,
WholeArchiveNeedsStatic,
};
pub(crate) struct LinkNameParser;
@@ -388,12 +391,7 @@ impl LinkParser {
cx.adcx().duplicate_key(item.span(), sym::cfg);
return true;
}
let Some(link_cfg) = item.args().list() else {
cx.adcx().expected_list(item.span(), item.args());
return true;
};
let Some(link_cfg) = link_cfg.single() else {
cx.adcx().expected_single_argument(item.span());
let Some(link_cfg) = cx.expect_single_element_list(item.args(), item.span()) else {
return true;
};
if !features.link_cfg() {
@@ -465,9 +463,33 @@ impl LinkParser {
pub(crate) struct LinkSectionParser;
fn check_link_section_macho(name: Symbol) -> Result<(), InvalidMachoSectionReason> {
let mut parts = name.as_str().split(',').map(|s| s.trim());
// The segment can be empty.
let _segment = parts.next();
// But the section is required.
let section = match parts.next() {
None | Some("") => return Err(InvalidMachoSectionReason::MissingSection),
Some(section) => section,
};
if section.len() > 16 {
return Err(InvalidMachoSectionReason::SectionTooLong { section: section.to_string() });
}
// LLVM also checks the other components of the section specifier, but that logic is hard to
// keep in sync. We skip it here for now, assuming that if you got that far you'll be able
// to interpret the LLVM errors.
Ok(())
}
impl<S: Stage> SingleAttributeParser<S> for LinkSectionParser {
const PATH: &[Symbol] = &[sym::link_section];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::WarnButFutureError;
const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: Some(Edition2024) };
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowListWarnRest(&[
Allow(Target::Static),
Allow(Target::Fn),
@@ -497,6 +519,18 @@ impl<S: Stage> SingleAttributeParser<S> for LinkSectionParser {
return None;
}
// We (currently) only validate macho section specifiers.
match cx.sess.target.binary_format {
BinaryFormat::MachO => match check_link_section_macho(name) {
Ok(()) => {}
Err(reason) => {
cx.emit_err(InvalidMachoSection { name_span: nv.value_span, reason });
return None;
}
},
BinaryFormat::Coff | BinaryFormat::Elf | BinaryFormat::Wasm | BinaryFormat::Xcoff => {}
}
Some(LinkSection { name, span: cx.attr_span })
}
}
@@ -504,7 +538,6 @@ impl<S: Stage> SingleAttributeParser<S> for LinkSectionParser {
pub(crate) struct ExportStableParser;
impl<S: Stage> NoArgsAttributeParser<S> for ExportStableParser {
const PATH: &[Symbol] = &[sym::export_stable];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); //FIXME Still checked fully in `check_attr.rs`
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::ExportStable;
}
@@ -512,7 +545,7 @@ impl<S: Stage> NoArgsAttributeParser<S> for ExportStableParser {
pub(crate) struct FfiConstParser;
impl<S: Stage> NoArgsAttributeParser<S> for FfiConstParser {
const PATH: &[Symbol] = &[sym::ffi_const];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: None };
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::ForeignFn)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::FfiConst;
}
@@ -520,7 +553,7 @@ impl<S: Stage> NoArgsAttributeParser<S> for FfiConstParser {
pub(crate) struct FfiPureParser;
impl<S: Stage> NoArgsAttributeParser<S> for FfiPureParser {
const PATH: &[Symbol] = &[sym::ffi_pure];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const SAFETY: AttributeSafety = AttributeSafety::Unsafe { unsafe_since: None };
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::ForeignFn)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::FfiPure;
}
@@ -528,7 +561,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for FfiPureParser {
pub(crate) struct RustcStdInternalSymbolParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcStdInternalSymbolParser {
const PATH: &[Symbol] = &[sym::rustc_std_internal_symbol];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::ForeignFn),
@@ -542,7 +574,6 @@ pub(crate) struct LinkOrdinalParser;
impl<S: Stage> SingleAttributeParser<S> for LinkOrdinalParser {
const PATH: &[Symbol] = &[sym::link_ordinal];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::ForeignFn),
Allow(Target::ForeignStatic),
@@ -583,7 +614,6 @@ pub(crate) struct LinkageParser;
impl<S: Stage> SingleAttributeParser<S> for LinkageParser {
const PATH: &[Symbol] = &[sym::linkage];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -666,7 +696,6 @@ pub(crate) struct NeedsAllocatorParser;
impl<S: Stage> NoArgsAttributeParser<S> for NeedsAllocatorParser {
const PATH: &[Symbol] = &[sym::needs_allocator];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::NeedsAllocator;
}
@@ -675,7 +704,6 @@ pub(crate) struct CompilerBuiltinsParser;
impl<S: Stage> NoArgsAttributeParser<S> for CompilerBuiltinsParser {
const PATH: &[Symbol] = &[sym::compiler_builtins];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::CompilerBuiltins;
}

View File

@@ -3,7 +3,6 @@ use super::prelude::*;
pub(crate) struct RustcAsPtrParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcAsPtrParser {
const PATH: &[Symbol] = &[sym::rustc_as_ptr];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -17,7 +16,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for RustcAsPtrParser {
pub(crate) struct RustcPubTransparentParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcPubTransparentParser {
const PATH: &[Symbol] = &[sym::rustc_pub_transparent];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Struct),
Allow(Target::Enum),
@@ -29,7 +27,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for RustcPubTransparentParser {
pub(crate) struct RustcPassByValueParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcPassByValueParser {
const PATH: &[Symbol] = &[sym::rustc_pass_by_value];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Struct),
Allow(Target::Enum),
@@ -41,7 +38,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for RustcPassByValueParser {
pub(crate) struct RustcShouldNotBeCalledOnConstItemsParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcShouldNotBeCalledOnConstItemsParser {
const PATH: &[Symbol] = &[sym::rustc_should_not_be_called_on_const_items];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Method(MethodKind::Inherent)),
Allow(Target::Method(MethodKind::TraitImpl)),

View File

@@ -3,7 +3,6 @@ use super::prelude::*;
pub(crate) struct LoopMatchParser;
impl<S: Stage> NoArgsAttributeParser<S> for LoopMatchParser {
const PATH: &[Symbol] = &[sym::loop_match];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Expression)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::LoopMatch;
}
@@ -11,7 +10,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for LoopMatchParser {
pub(crate) struct ConstContinueParser;
impl<S: Stage> NoArgsAttributeParser<S> for ConstContinueParser {
const PATH: &[Symbol] = &[sym::const_continue];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Expression)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::ConstContinue;
}

View File

@@ -142,7 +142,7 @@ impl<S: Stage> SingleAttributeParser<S> for MacroExportParser {
let local_inner_macros = match args {
ArgParser::NoArgs => false,
ArgParser::List(list) => {
let Some(l) = list.single() else {
let Some(l) = list.as_single() else {
cx.adcx().warn_ill_formed_attribute_input(INVALID_MACRO_EXPORT_ARGUMENTS);
return None;
};
@@ -167,7 +167,6 @@ pub(crate) struct CollapseDebugInfoParser;
impl<S: Stage> SingleAttributeParser<S> for CollapseDebugInfoParser {
const PATH: &[Symbol] = &[sym::collapse_debuginfo];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const TEMPLATE: AttributeTemplate = template!(
List: &["no", "external", "yes"],
"https://doc.rust-lang.org/reference/attributes/debugger.html#the-collapse_debuginfo-attribute"
@@ -175,15 +174,7 @@ impl<S: Stage> SingleAttributeParser<S> for CollapseDebugInfoParser {
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::MacroDef)]);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let Some(single) = list.single() else {
cx.adcx().expected_single_argument(list.span);
return None;
};
let single = cx.expect_single_element_list(args, cx.attr_span)?;
let Some(mi) = single.meta_item() else {
cx.adcx().expected_not_literal(single.span());
return None;
@@ -211,7 +202,6 @@ pub(crate) struct RustcProcMacroDeclsParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcProcMacroDeclsParser {
const PATH: &[Symbol] = &[sym::rustc_proc_macro_decls];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Static)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcProcMacroDecls;
}

View File

@@ -18,6 +18,7 @@ use std::marker::PhantomData;
use rustc_feature::{AttributeTemplate, template};
use rustc_hir::attrs::AttributeKind;
use rustc_span::edition::Edition;
use rustc_span::{Span, Symbol};
use thin_vec::ThinVec;
@@ -97,6 +98,7 @@ pub(crate) trait AttributeParser<S: Stage>: Default + 'static {
/// If an attribute has this symbol, the `accept` function will be called on it.
const ATTRIBUTES: AcceptMapping<Self, S>;
const ALLOWED_TARGETS: AllowedTargets;
const SAFETY: AttributeSafety = AttributeSafety::Normal;
/// The parser has gotten a chance to accept the attributes on an item,
/// here it can produce an attribute.
@@ -126,7 +128,8 @@ pub(crate) trait SingleAttributeParser<S: Stage>: 'static {
/// Configures what to do when when the same attribute is
/// applied more than once on the same syntax node.
const ON_DUPLICATE: OnDuplicate<S>;
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const SAFETY: AttributeSafety = AttributeSafety::Normal;
const ALLOWED_TARGETS: AllowedTargets;
@@ -158,13 +161,14 @@ impl<T: SingleAttributeParser<S>, S: Stage> AttributeParser<S> for Single<T, S>
if let Some(pa) = T::convert(cx, args) {
if let Some((_, used)) = group.1 {
T::ON_DUPLICATE.exec::<T>(cx, used, cx.attr_span);
} else {
group.1 = Some((pa, cx.attr_span));
}
group.1 = Some((pa, cx.attr_span));
}
},
)];
const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
const SAFETY: AttributeSafety = T::SAFETY;
fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
Some(self.1?.0)
@@ -217,6 +221,18 @@ impl<S: Stage> OnDuplicate<S> {
}
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum AttributeSafety {
/// Normal attribute that does not need `#[unsafe(...)]`
Normal,
/// Unsafe attribute that requires safety obligations to be discharged.
///
/// An error is emitted when `#[unsafe(...)]` is omitted, except when the attribute's edition
/// is less than the one stored in `unsafe_since`. This handles attributes that were safe in
/// earlier editions, but become unsafe in later ones.
Unsafe { unsafe_since: Option<Edition> },
}
/// An even simpler version of [`SingleAttributeParser`]:
/// now automatically check that there are no arguments provided to the attribute.
///
@@ -224,8 +240,9 @@ impl<S: Stage> OnDuplicate<S> {
//
pub(crate) trait NoArgsAttributeParser<S: Stage>: 'static {
const PATH: &[Symbol];
const ON_DUPLICATE: OnDuplicate<S>;
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets;
const SAFETY: AttributeSafety = AttributeSafety::Normal;
/// Create the [`AttributeKind`] given attribute's [`Span`].
const CREATE: fn(Span) -> AttributeKind;
@@ -242,6 +259,7 @@ impl<T: NoArgsAttributeParser<S>, S: Stage> Default for WithoutArgs<T, S> {
impl<T: NoArgsAttributeParser<S>, S: Stage> SingleAttributeParser<S> for WithoutArgs<T, S> {
const PATH: &[Symbol] = T::PATH;
const ON_DUPLICATE: OnDuplicate<S> = T::ON_DUPLICATE;
const SAFETY: AttributeSafety = T::SAFETY;
const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
const TEMPLATE: AttributeTemplate = template!(Word);
@@ -271,6 +289,7 @@ pub(crate) trait CombineAttributeParser<S: Stage>: 'static {
/// For example, individual representations from `#[repr(...)]` attributes into an `AttributeKind::Repr(x)`,
/// where `x` is a vec of these individual reprs.
const CONVERT: ConvertFn<Self::Item>;
const SAFETY: AttributeSafety = AttributeSafety::Normal;
const ALLOWED_TARGETS: AllowedTargets;
@@ -312,6 +331,7 @@ impl<T: CombineAttributeParser<S>, S: Stage> AttributeParser<S> for Combine<T, S
group.items.extend(T::extend(cx, args))
})];
const ALLOWED_TARGETS: AllowedTargets = T::ALLOWED_TARGETS;
const SAFETY: AttributeSafety = T::SAFETY;
fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
if let Some(first_span) = self.first_span {

View File

@@ -4,7 +4,6 @@ pub(crate) struct MustNotSuspendParser;
impl<S: Stage> SingleAttributeParser<S> for MustNotSuspendParser {
const PATH: &[rustc_span::Symbol] = &[sym::must_not_suspend];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Struct),
Allow(Target::Enum),

View File

@@ -2,7 +2,7 @@ use rustc_hir::Target;
use rustc_hir::attrs::AttributeKind;
use rustc_span::{Span, Symbol, sym};
use crate::attributes::{NoArgsAttributeParser, OnDuplicate};
use crate::attributes::NoArgsAttributeParser;
use crate::context::Stage;
use crate::target_checking::AllowedTargets;
use crate::target_checking::Policy::Allow;
@@ -11,7 +11,6 @@ pub(crate) struct PinV2Parser;
impl<S: Stage> NoArgsAttributeParser<S> for PinV2Parser {
const PATH: &[Symbol] = &[sym::pin_v2];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Enum),
Allow(Target::Struct),

View File

@@ -1,4 +1,4 @@
use rustc_hir::lints::AttributeLintKind;
use rustc_errors::Diagnostic;
use rustc_session::lint::builtin::AMBIGUOUS_DERIVE_HELPERS;
use super::prelude::*;
@@ -9,7 +9,6 @@ const PROC_MACRO_ALLOWED_TARGETS: AllowedTargets =
pub(crate) struct ProcMacroParser;
impl<S: Stage> NoArgsAttributeParser<S> for ProcMacroParser {
const PATH: &[Symbol] = &[sym::proc_macro];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = PROC_MACRO_ALLOWED_TARGETS;
const CREATE: fn(Span) -> AttributeKind = AttributeKind::ProcMacro;
}
@@ -17,7 +16,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for ProcMacroParser {
pub(crate) struct ProcMacroAttributeParser;
impl<S: Stage> NoArgsAttributeParser<S> for ProcMacroAttributeParser {
const PATH: &[Symbol] = &[sym::proc_macro_attribute];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = PROC_MACRO_ALLOWED_TARGETS;
const CREATE: fn(Span) -> AttributeKind = AttributeKind::ProcMacroAttribute;
}
@@ -25,7 +23,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for ProcMacroAttributeParser {
pub(crate) struct ProcMacroDeriveParser;
impl<S: Stage> SingleAttributeParser<S> for ProcMacroDeriveParser {
const PATH: &[Symbol] = &[sym::proc_macro_derive];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = PROC_MACRO_ALLOWED_TARGETS;
const TEMPLATE: AttributeTemplate = template!(
List: &["TraitName", "TraitName, attributes(name1, name2, ...)"],
@@ -45,7 +42,6 @@ impl<S: Stage> SingleAttributeParser<S> for ProcMacroDeriveParser {
pub(crate) struct RustcBuiltinMacroParser;
impl<S: Stage> SingleAttributeParser<S> for RustcBuiltinMacroParser {
const PATH: &[Symbol] = &[sym::rustc_builtin_macro];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::MacroDef)]);
const TEMPLATE: AttributeTemplate =
template!(List: &["TraitName", "TraitName, attributes(name1, name2, ...)"]);
@@ -61,7 +57,7 @@ fn parse_derive_like<S: Stage>(
args: &ArgParser,
trait_name_mandatory: bool,
) -> Option<(Option<Symbol>, ThinVec<Symbol>)> {
let Some(list) = args.list() else {
let Some(list) = args.as_list() else {
// For #[rustc_builtin_macro], it is permitted to leave out the trait name
if args.no_args().is_ok() && !trait_name_mandatory {
return Some((None, ThinVec::new()));
@@ -105,10 +101,7 @@ fn parse_derive_like<S: Stage>(
cx.adcx().expected_specific_argument(attrs.span(), &[sym::attributes]);
return None;
}
let Some(attr_list) = attr_list.args().list() else {
cx.adcx().expected_list(attrs.span(), attr_list.args());
return None;
};
let attr_list = cx.expect_list(attr_list.args(), attrs.span())?;
// Parse item in `attributes(...)` argument
for attr in attr_list.mixed() {
@@ -129,9 +122,9 @@ fn parse_derive_like<S: Stage>(
return None;
}
if rustc_feature::is_builtin_attr_name(ident.name) {
cx.emit_lint(
cx.emit_dyn_lint(
AMBIGUOUS_DERIVE_HELPERS,
AttributeLintKind::AmbiguousDeriveHelpers,
|dcx, level| crate::errors::AmbiguousDeriveHelpers.into_diag(dcx, level),
ident.span,
);
}

View File

@@ -5,7 +5,6 @@ use rustc_hir::Target;
use rustc_hir::attrs::{AttributeKind, MirDialect, MirPhase};
use rustc_span::{Span, Symbol, sym};
use super::OnDuplicate;
use crate::attributes::SingleAttributeParser;
use crate::context::{AcceptContext, Stage};
use crate::parser::ArgParser;
@@ -18,18 +17,12 @@ pub(crate) struct CustomMirParser;
impl<S: Stage> SingleAttributeParser<S> for CustomMirParser {
const PATH: &[rustc_span::Symbol] = &[sym::custom_mir];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const TEMPLATE: AttributeTemplate = template!(List: &[r#"dialect = "...", phase = "...""#]);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let list = cx.expect_list(args, cx.attr_span)?;
let mut dialect = None;
let mut phase = None;
@@ -82,7 +75,7 @@ fn extract_value<S: Stage>(
}
let Some(val) = arg.name_value() else {
cx.adcx().expected_single_argument(arg.span().unwrap_or(span));
cx.adcx().expected_name_value(span, Some(key));
*failed = true;
return;
};

View File

@@ -32,9 +32,7 @@ impl<S: Stage> CombineAttributeParser<S> for ReprParser {
) -> impl IntoIterator<Item = Self::Item> {
let mut reprs = Vec::new();
let Some(list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
let Some(list) = cx.expect_list(args, cx.attr_span) else {
return reprs;
};
@@ -197,7 +195,7 @@ fn parse_repr_align<S: Stage>(
) -> Option<ReprAttr> {
use AlignKind::*;
let Some(align) = list.single() else {
let Some(align) = list.as_single() else {
match align_kind {
Packed => {
cx.emit_err(session_diagnostics::IncorrectReprFormatPackedOneOrZeroArg {
@@ -296,8 +294,7 @@ impl RustcAlignParser {
cx.adcx().expected_list(attr_span, args);
}
ArgParser::List(list) => {
let Some(align) = list.single() else {
cx.adcx().expected_single_argument(list.span);
let Some(align) = cx.expect_single(list) else {
return;
};

View File

@@ -4,7 +4,6 @@ pub(crate) struct RustcAllocatorParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcAllocatorParser {
const PATH: &[Symbol] = &[sym::rustc_allocator];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcAllocator;
@@ -14,7 +13,6 @@ pub(crate) struct RustcAllocatorZeroedParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcAllocatorZeroedParser {
const PATH: &[Symbol] = &[sym::rustc_allocator_zeroed];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcAllocatorZeroed;
@@ -24,7 +22,6 @@ pub(crate) struct RustcAllocatorZeroedVariantParser;
impl<S: Stage> SingleAttributeParser<S> for RustcAllocatorZeroedVariantParser {
const PATH: &[Symbol] = &[sym::rustc_allocator_zeroed_variant];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]);
const TEMPLATE: AttributeTemplate = template!(NameValueStr: "function");
@@ -43,7 +40,6 @@ pub(crate) struct RustcDeallocatorParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDeallocatorParser {
const PATH: &[Symbol] = &[sym::rustc_deallocator];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcDeallocator;
@@ -53,7 +49,6 @@ pub(crate) struct RustcReallocatorParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcReallocatorParser {
const PATH: &[Symbol] = &[sym::rustc_reallocator];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::Fn), Allow(Target::ForeignFn)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcReallocator;

View File

@@ -10,7 +10,6 @@ pub(crate) struct RustcDumpUserArgsParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDumpUserArgsParser {
const PATH: &[Symbol] = &[sym::rustc_dump_user_args];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcDumpUserArgs;
}
@@ -19,7 +18,6 @@ pub(crate) struct RustcDumpDefParentsParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDumpDefParentsParser {
const PATH: &[Symbol] = &[sym::rustc_dump_def_parents];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcDumpDefParents;
}
@@ -37,7 +35,6 @@ impl<S: Stage> SingleAttributeParser<S> for RustcDumpDefPathParser {
Allow(Target::ForeignStatic),
Allow(Target::Impl { of_trait: false }),
]);
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const TEMPLATE: AttributeTemplate = template!(Word);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
if let Err(span) = args.no_args() {
@@ -52,7 +49,6 @@ pub(crate) struct RustcDumpHiddenTypeOfOpaquesParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDumpHiddenTypeOfOpaquesParser {
const PATH: &[Symbol] = &[sym::rustc_dump_hidden_type_of_opaques];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcDumpHiddenTypeOfOpaques;
}
@@ -61,7 +57,6 @@ pub(crate) struct RustcDumpInferredOutlivesParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDumpInferredOutlivesParser {
const PATH: &[Symbol] = &[sym::rustc_dump_inferred_outlives];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Struct),
Allow(Target::Enum),
@@ -75,7 +70,6 @@ pub(crate) struct RustcDumpItemBoundsParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDumpItemBoundsParser {
const PATH: &[Symbol] = &[sym::rustc_dump_item_bounds];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::AssocTy)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcDumpItemBounds;
}
@@ -102,9 +96,7 @@ impl<S: Stage> CombineAttributeParser<S> for RustcDumpLayoutParser {
cx: &mut AcceptContext<'_, '_, S>,
args: &ArgParser,
) -> impl IntoIterator<Item = Self::Item> {
let ArgParser::List(items) = args else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
let Some(items) = cx.expect_list(args, cx.attr_span) else {
return vec![];
};
@@ -148,7 +140,6 @@ pub(crate) struct RustcDumpObjectLifetimeDefaultsParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDumpObjectLifetimeDefaultsParser {
const PATH: &[Symbol] = &[sym::rustc_dump_object_lifetime_defaults];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::AssocConst),
Allow(Target::AssocTy),
@@ -175,7 +166,6 @@ pub(crate) struct RustcDumpPredicatesParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDumpPredicatesParser {
const PATH: &[Symbol] = &[sym::rustc_dump_predicates];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::AssocConst),
Allow(Target::AssocTy),
@@ -212,7 +202,6 @@ impl<S: Stage> SingleAttributeParser<S> for RustcDumpSymbolNameParser {
Allow(Target::ForeignStatic),
Allow(Target::Impl { of_trait: false }),
]);
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const TEMPLATE: AttributeTemplate = template!(Word);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
if let Err(span) = args.no_args() {
@@ -227,7 +216,6 @@ pub(crate) struct RustcDumpVariancesParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDumpVariancesParser {
const PATH: &[Symbol] = &[sym::rustc_dump_variances];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Enum),
Allow(Target::Fn),
@@ -245,7 +233,6 @@ pub(crate) struct RustcDumpVariancesOfOpaquesParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDumpVariancesOfOpaquesParser {
const PATH: &[Symbol] = &[sym::rustc_dump_variances_of_opaques];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcDumpVariancesOfOpaques;
}
@@ -254,7 +241,6 @@ pub(crate) struct RustcDumpVtableParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDumpVtableParser {
const PATH: &[Symbol] = &[sym::rustc_dump_vtable];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Impl { of_trait: true }),
Allow(Target::TyAlias),

View File

@@ -6,11 +6,11 @@ use rustc_hir::attrs::{
BorrowckGraphvizFormatKind, CguFields, CguKind, DivergingBlockBehavior,
DivergingFallbackBehavior, RustcCleanAttribute, RustcCleanQueries, RustcMirKind,
};
use rustc_session::errors;
use rustc_span::Symbol;
use super::prelude::*;
use super::util::parse_single_integer;
use crate::errors;
use crate::session_diagnostics::{
AttributeRequiresOpt, CguFieldsMissing, RustcScalableVectorCountOutOfRange, UnknownLangItem,
};
@@ -19,7 +19,6 @@ pub(crate) struct RustcMainParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcMainParser {
const PATH: &[Symbol] = &[sym::rustc_main];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcMain;
}
@@ -28,15 +27,10 @@ pub(crate) struct RustcMustImplementOneOfParser;
impl<S: Stage> SingleAttributeParser<S> for RustcMustImplementOneOfParser {
const PATH: &[Symbol] = &[sym::rustc_must_implement_one_of];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]);
const TEMPLATE: AttributeTemplate = template!(List: &["function1, function2, ..."]);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(list) = args.list() else {
let span = cx.attr_span;
cx.adcx().expected_list(span, args);
return None;
};
let list = cx.expect_list(args, cx.attr_span)?;
let mut fn_names = ThinVec::new();
@@ -74,7 +68,6 @@ pub(crate) struct RustcNeverReturnsNullPtrParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcNeverReturnsNullPtrParser {
const PATH: &[Symbol] = &[sym::rustc_never_returns_null_ptr];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -88,7 +81,6 @@ pub(crate) struct RustcNoImplicitAutorefsParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcNoImplicitAutorefsParser {
const PATH: &[Symbol] = &[sym::rustc_no_implicit_autorefs];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -104,7 +96,6 @@ pub(crate) struct RustcLayoutScalarValidRangeStartParser;
impl<S: Stage> SingleAttributeParser<S> for RustcLayoutScalarValidRangeStartParser {
const PATH: &[Symbol] = &[sym::rustc_layout_scalar_valid_range_start];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Struct)]);
const TEMPLATE: AttributeTemplate = template!(List: &["start"]);
@@ -118,7 +109,6 @@ pub(crate) struct RustcLayoutScalarValidRangeEndParser;
impl<S: Stage> SingleAttributeParser<S> for RustcLayoutScalarValidRangeEndParser {
const PATH: &[Symbol] = &[sym::rustc_layout_scalar_valid_range_end];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Struct)]);
const TEMPLATE: AttributeTemplate = template!(List: &["end"]);
@@ -132,16 +122,11 @@ pub(crate) struct RustcLegacyConstGenericsParser;
impl<S: Stage> SingleAttributeParser<S> for RustcLegacyConstGenericsParser {
const PATH: &[Symbol] = &[sym::rustc_legacy_const_generics];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const TEMPLATE: AttributeTemplate = template!(List: &["N"]);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let ArgParser::List(meta_items) = args else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let meta_items = cx.expect_list(args, cx.attr_span)?;
let mut parsed_indexes = ThinVec::new();
let mut errored = false;
@@ -176,7 +161,6 @@ pub(crate) struct RustcInheritOverflowChecksParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcInheritOverflowChecksParser {
const PATH: &[Symbol] = &[sym::rustc_inherit_overflow_checks];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -190,15 +174,10 @@ pub(crate) struct RustcLintOptDenyFieldAccessParser;
impl<S: Stage> SingleAttributeParser<S> for RustcLintOptDenyFieldAccessParser {
const PATH: &[Symbol] = &[sym::rustc_lint_opt_deny_field_access];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Field)]);
const TEMPLATE: AttributeTemplate = template!(Word);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(arg) = args.list().and_then(MetaItemListParser::single) else {
let attr_span = cx.attr_span;
cx.adcx().expected_single_argument(attr_span);
return None;
};
let arg = cx.expect_single_element_list(args, cx.attr_span)?;
let MetaItemOrLitParser::Lit(MetaItemLit { kind: LitKind::Str(lint_message, _), .. }) = arg
else {
@@ -214,7 +193,6 @@ pub(crate) struct RustcLintOptTyParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcLintOptTyParser {
const PATH: &[Symbol] = &[sym::rustc_lint_opt_ty];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Struct)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcLintOptTy;
}
@@ -224,11 +202,7 @@ fn parse_cgu_fields<S: Stage>(
args: &ArgParser,
accepts_kind: bool,
) -> Option<(Symbol, Symbol, Option<CguKind>)> {
let Some(args) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let args = cx.expect_list(args, cx.attr_span)?;
let mut cfg = None::<(Symbol, Span)>;
let mut module = None::<(Symbol, Span)>;
@@ -363,7 +337,6 @@ pub(crate) struct RustcDeprecatedSafe2024Parser;
impl<S: Stage> SingleAttributeParser<S> for RustcDeprecatedSafe2024Parser {
const PATH: &[Symbol] = &[sym::rustc_deprecated_safe_2024];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -374,19 +347,10 @@ impl<S: Stage> SingleAttributeParser<S> for RustcDeprecatedSafe2024Parser {
const TEMPLATE: AttributeTemplate = template!(List: &[r#"audit_that = "...""#]);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(args) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let Some(single) = args.single() else {
cx.adcx().expected_single_argument(args.span);
return None;
};
let single = cx.expect_single_element_list(args, cx.attr_span)?;
let Some(arg) = single.meta_item() else {
cx.adcx().expected_name_value(args.span, None);
cx.adcx().expected_name_value(single.span(), None);
return None;
};
@@ -413,7 +377,6 @@ pub(crate) struct RustcConversionSuggestionParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcConversionSuggestionParser {
const PATH: &[Symbol] = &[sym::rustc_conversion_suggestion];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -428,7 +391,6 @@ pub(crate) struct RustcCaptureAnalysisParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcCaptureAnalysisParser {
const PATH: &[Symbol] = &[sym::rustc_capture_analysis];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Closure)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcCaptureAnalysis;
}
@@ -437,7 +399,6 @@ pub(crate) struct RustcNeverTypeOptionsParser;
impl<S: Stage> SingleAttributeParser<S> for RustcNeverTypeOptionsParser {
const PATH: &[Symbol] = &[sym::rustc_never_type_options];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const TEMPLATE: AttributeTemplate = template!(List: &[
r#"fallback = "unit", "never", "no""#,
@@ -445,11 +406,7 @@ impl<S: Stage> SingleAttributeParser<S> for RustcNeverTypeOptionsParser {
]);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let list = cx.expect_list(args, cx.attr_span)?;
let mut fallback = None::<Ident>;
let mut diverging_block_default = None::<Ident>;
@@ -520,7 +477,6 @@ pub(crate) struct RustcTrivialFieldReadsParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcTrivialFieldReadsParser {
const PATH: &[Symbol] = &[sym::rustc_trivial_field_reads];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcTrivialFieldReads;
}
@@ -529,7 +485,6 @@ pub(crate) struct RustcNoMirInlineParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcNoMirInlineParser {
const PATH: &[Symbol] = &[sym::rustc_no_mir_inline];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -540,11 +495,25 @@ impl<S: Stage> NoArgsAttributeParser<S> for RustcNoMirInlineParser {
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcNoMirInline;
}
pub(crate) struct RustcNoWritableParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcNoWritableParser {
const PATH: &[Symbol] = &[sym::rustc_no_writable];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Closure),
Allow(Target::Method(MethodKind::Inherent)),
Allow(Target::Method(MethodKind::TraitImpl)),
Allow(Target::Method(MethodKind::Trait { body: true })),
]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcNoWritable;
}
pub(crate) struct RustcLintQueryInstabilityParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcLintQueryInstabilityParser {
const PATH: &[Symbol] = &[sym::rustc_lint_query_instability];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -559,7 +528,6 @@ pub(crate) struct RustcRegionsParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcRegionsParser {
const PATH: &[Symbol] = &[sym::rustc_regions];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -575,7 +543,6 @@ pub(crate) struct RustcLintUntrackedQueryInformationParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcLintUntrackedQueryInformationParser {
const PATH: &[Symbol] = &[sym::rustc_lint_untracked_query_information];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -591,7 +558,6 @@ pub(crate) struct RustcSimdMonomorphizeLaneLimitParser;
impl<S: Stage> SingleAttributeParser<S> for RustcSimdMonomorphizeLaneLimitParser {
const PATH: &[Symbol] = &[sym::rustc_simd_monomorphize_lane_limit];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Struct)]);
const TEMPLATE: AttributeTemplate = template!(NameValueStr: "N");
@@ -609,7 +575,6 @@ pub(crate) struct RustcScalableVectorParser;
impl<S: Stage> SingleAttributeParser<S> for RustcScalableVectorParser {
const PATH: &[Symbol] = &[sym::rustc_scalable_vector];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Struct)]);
const TEMPLATE: AttributeTemplate = template!(Word, List: &["count"]);
@@ -634,7 +599,6 @@ pub(crate) struct LangParser;
impl<S: Stage> SingleAttributeParser<S> for LangParser {
const PATH: &[Symbol] = &[sym::lang];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); // Targets are checked per lang item in `rustc_passes`
const TEMPLATE: AttributeTemplate = template!(NameValueStr: "name");
@@ -660,7 +624,6 @@ pub(crate) struct RustcHasIncoherentInherentImplsParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcHasIncoherentInherentImplsParser {
const PATH: &[Symbol] = &[sym::rustc_has_incoherent_inherent_impls];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Trait),
Allow(Target::Struct),
@@ -675,7 +638,6 @@ pub(crate) struct PanicHandlerParser;
impl<S: Stage> NoArgsAttributeParser<S> for PanicHandlerParser {
const PATH: &[Symbol] = &[sym::panic_handler];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); // Targets are checked per lang item in `rustc_passes`
const CREATE: fn(Span) -> AttributeKind = |span| AttributeKind::Lang(LangItem::PanicImpl, span);
}
@@ -684,7 +646,6 @@ pub(crate) struct RustcNounwindParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcNounwindParser {
const PATH: &[Symbol] = &[sym::rustc_nounwind];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::ForeignFn),
@@ -699,7 +660,6 @@ pub(crate) struct RustcOffloadKernelParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcOffloadKernelParser {
const PATH: &[Symbol] = &[sym::rustc_offload_kernel];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcOffloadKernel;
}
@@ -727,9 +687,7 @@ impl<S: Stage> CombineAttributeParser<S> for RustcMirParser {
cx: &mut AcceptContext<'_, '_, S>,
args: &ArgParser,
) -> impl IntoIterator<Item = Self::Item> {
let Some(list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
let Some(list) = cx.expect_list(args, cx.attr_span) else {
return ThinVec::new();
};
@@ -798,7 +756,6 @@ pub(crate) struct RustcNonConstTraitMethodParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcNonConstTraitMethodParser {
const PATH: &[Symbol] = &[sym::rustc_non_const_trait_method];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Method(MethodKind::Trait { body: true })),
Allow(Target::Method(MethodKind::Trait { body: false })),
@@ -850,11 +807,8 @@ impl<S: Stage> CombineAttributeParser<S> for RustcCleanParser {
if !cx.cx.sess.opts.unstable_opts.query_dep_graph {
cx.emit_err(AttributeRequiresOpt { span: cx.attr_span, opt: "-Z query-dep-graph" });
}
let Some(list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let list = cx.expect_list(args, cx.attr_span)?;
let mut except = None;
let mut loaded_from_disk = None;
let mut cfg = None;
@@ -917,8 +871,6 @@ pub(crate) struct RustcIfThisChangedParser;
impl<S: Stage> SingleAttributeParser<S> for RustcIfThisChangedParser {
const PATH: &[Symbol] = &[sym::rustc_if_this_changed];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
// tidy-alphabetical-start
Allow(Target::AssocConst),
@@ -953,11 +905,7 @@ impl<S: Stage> SingleAttributeParser<S> for RustcIfThisChangedParser {
match args {
ArgParser::NoArgs => Some(AttributeKind::RustcIfThisChanged(cx.attr_span, None)),
ArgParser::List(list) => {
let Some(item) = list.single() else {
let attr_span = cx.attr_span;
cx.adcx().expected_single_argument(attr_span);
return None;
};
let item = cx.expect_single(list)?;
let Some(ident) = item.meta_item().and_then(|item| item.ident()) else {
cx.adcx().expected_identifier(item.span());
return None;
@@ -1015,11 +963,7 @@ impl<S: Stage> CombineAttributeParser<S> for RustcThenThisWouldNeedParser {
if !cx.cx.sess.opts.unstable_opts.query_dep_graph {
cx.emit_err(AttributeRequiresOpt { span: cx.attr_span, opt: "-Z query-dep-graph" });
}
let Some(item) = args.list().and_then(|l| l.single()) else {
let inner_span = cx.inner_span;
cx.adcx().expected_single_argument(inner_span);
return None;
};
let item = cx.expect_single_element_list(args, cx.attr_span)?;
let Some(ident) = item.meta_item().and_then(|item| item.ident()) else {
cx.adcx().expected_identifier(item.span());
return None;
@@ -1032,7 +976,6 @@ pub(crate) struct RustcInsignificantDtorParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcInsignificantDtorParser {
const PATH: &[Symbol] = &[sym::rustc_insignificant_dtor];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Enum),
Allow(Target::Struct),
@@ -1045,7 +988,6 @@ pub(crate) struct RustcEffectiveVisibilityParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcEffectiveVisibilityParser {
const PATH: &[Symbol] = &[sym::rustc_effective_visibility];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Use),
Allow(Target::Static),
@@ -1084,7 +1026,6 @@ pub(crate) struct RustcDiagnosticItemParser;
impl<S: Stage> SingleAttributeParser<S> for RustcDiagnosticItemParser {
const PATH: &[Symbol] = &[sym::rustc_diagnostic_item];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Trait),
Allow(Target::Struct),
@@ -1123,7 +1064,6 @@ pub(crate) struct RustcDoNotConstCheckParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDoNotConstCheckParser {
const PATH: &[Symbol] = &[sym::rustc_do_not_const_check];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -1138,7 +1078,6 @@ pub(crate) struct RustcNonnullOptimizationGuaranteedParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcNonnullOptimizationGuaranteedParser {
const PATH: &[Symbol] = &[sym::rustc_nonnull_optimization_guaranteed];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Struct)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcNonnullOptimizationGuaranteed;
}
@@ -1147,7 +1086,6 @@ pub(crate) struct RustcStrictCoherenceParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcStrictCoherenceParser {
const PATH: &[Symbol] = &[sym::rustc_strict_coherence];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Trait),
Allow(Target::Struct),
@@ -1162,7 +1100,6 @@ pub(crate) struct RustcReservationImplParser;
impl<S: Stage> SingleAttributeParser<S> for RustcReservationImplParser {
const PATH: &[Symbol] = &[sym::rustc_reservation_impl];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::Impl { of_trait: true })]);
@@ -1188,7 +1125,6 @@ pub(crate) struct PreludeImportParser;
impl<S: Stage> NoArgsAttributeParser<S> for PreludeImportParser {
const PATH: &[Symbol] = &[sym::prelude_import];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Use)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::PreludeImport;
}
@@ -1197,7 +1133,6 @@ pub(crate) struct RustcDocPrimitiveParser;
impl<S: Stage> SingleAttributeParser<S> for RustcDocPrimitiveParser {
const PATH: &[Symbol] = &[sym::rustc_doc_primitive];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Mod)]);
const TEMPLATE: AttributeTemplate = template!(NameValueStr: "primitive name");
@@ -1221,7 +1156,6 @@ pub(crate) struct RustcIntrinsicParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcIntrinsicParser {
const PATH: &[Symbol] = &[sym::rustc_intrinsic];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcIntrinsic;
}
@@ -1230,7 +1164,6 @@ pub(crate) struct RustcIntrinsicConstStableIndirectParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcIntrinsicConstStableIndirectParser {
const PATH: &'static [Symbol] = &[sym::rustc_intrinsic_const_stable_indirect];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcIntrinsicConstStableIndirect;
}
@@ -1239,7 +1172,6 @@ pub(crate) struct RustcExhaustiveParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcExhaustiveParser {
const PATH: &'static [Symbol] = &[sym::rustc_must_match_exhaustively];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Enum)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcMustMatchExhaustively;
}

View File

@@ -3,7 +3,6 @@ use super::prelude::*;
pub(crate) struct MayDangleParser;
impl<S: Stage> NoArgsAttributeParser<S> for MayDangleParser {
const PATH: &[Symbol] = &[sym::may_dangle];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); //FIXME Still checked fully in `check_attr.rs`
const CREATE: fn(span: Span) -> AttributeKind = AttributeKind::MayDangle;
}

View File

@@ -2,6 +2,7 @@ use std::num::NonZero;
use rustc_errors::ErrorGuaranteed;
use rustc_feature::ACCEPTED_LANG_FEATURES;
use rustc_hir::attrs::UnstableRemovedFeature;
use rustc_hir::target::GenericParamKind;
use rustc_hir::{
DefaultBodyStability, MethodKind, PartialConstStability, Stability, StabilityLevel,
@@ -310,11 +311,7 @@ pub(crate) fn parse_stability<S: Stage>(
let mut feature = None;
let mut since = None;
let ArgParser::List(list) = args else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let list = cx.expect_list(args, cx.attr_span)?;
for param in list.mixed() {
let param_span = param.span();
@@ -382,11 +379,7 @@ pub(crate) fn parse_unstability<S: Stage>(
let mut implied_by = None;
let mut old_name = None;
let ArgParser::List(list) = args else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let list = cx.expect_list(args, cx.attr_span)?;
for param in list.mixed() {
let Some(param) = param.meta_item() else {
@@ -476,3 +469,85 @@ pub(crate) fn parse_unstability<S: Stage>(
(Err(ErrorGuaranteed { .. }), _) | (_, Err(ErrorGuaranteed { .. })) => None,
}
}
pub(crate) struct UnstableRemovedParser;
impl<S: Stage> CombineAttributeParser<S> for UnstableRemovedParser {
type Item = UnstableRemovedFeature;
const PATH: &[Symbol] = &[sym::unstable_removed];
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const TEMPLATE: AttributeTemplate =
template!(List: &[r#"feature = "name", reason = "...", link = "...", since = "version""#]);
const CONVERT: ConvertFn<Self::Item> = |items, _| AttributeKind::UnstableRemoved(items);
fn extend(
cx: &mut AcceptContext<'_, '_, S>,
args: &ArgParser,
) -> impl IntoIterator<Item = Self::Item> {
let mut feature = None;
let mut reason = None;
let mut link = None;
let mut since = None;
if !cx.features().staged_api() {
cx.emit_err(session_diagnostics::StabilityOutsideStd { span: cx.attr_span });
return None;
}
let list = cx.expect_list(args, cx.attr_span)?;
for param in list.mixed() {
let Some(param) = param.meta_item() else {
cx.adcx().expected_not_literal(param.span());
return None;
};
let Some(word) = param.path().word() else {
cx.adcx().expected_specific_argument(
param.span(),
&[sym::feature, sym::reason, sym::link, sym::since],
);
return None;
};
match word.name {
sym::feature => insert_value_into_option_or_error(cx, &param, &mut feature, word)?,
sym::since => insert_value_into_option_or_error(cx, &param, &mut since, word)?,
sym::reason => insert_value_into_option_or_error(cx, &param, &mut reason, word)?,
sym::link => insert_value_into_option_or_error(cx, &param, &mut link, word)?,
_ => {
cx.adcx().expected_specific_argument(
param.span(),
&[sym::feature, sym::reason, sym::link, sym::since],
);
return None;
}
}
}
// Check all the arguments are present
let Some(feature) = feature else {
cx.adcx().missing_name_value(list.span, sym::feature);
return None;
};
let Some(reason) = reason else {
cx.adcx().missing_name_value(list.span, sym::reason);
return None;
};
let Some(link) = link else {
cx.adcx().missing_name_value(list.span, sym::link);
return None;
};
let Some(since) = since else {
cx.adcx().missing_name_value(list.span, sym::since);
return None;
};
let Some(version) = parse_version(since) else {
cx.emit_err(session_diagnostics::InvalidSince { span: cx.attr_span });
return None;
};
Some(UnstableRemovedFeature { feature, reason, link, since: version })
}
}

View File

@@ -28,10 +28,11 @@ impl<S: Stage> SingleAttributeParser<S> for IgnoreParser {
Some(str_value)
}
ArgParser::List(list) => {
let help = list.single().and_then(|item| item.meta_item()).and_then(|item| {
item.args().no_args().ok()?;
Some(item.path().to_string())
});
let help =
list.as_single().and_then(|item| item.meta_item()).and_then(|item| {
item.args().no_args().ok()?;
Some(item.path().to_string())
});
cx.adcx().warn_ill_formed_attribute_input_with_help(
ILL_FORMED_ATTRIBUTE_INPUT,
help,
@@ -71,10 +72,7 @@ impl<S: Stage> SingleAttributeParser<S> for ShouldPanicParser {
Some(str_value)
}
ArgParser::List(list) => {
let Some(single) = list.single() else {
cx.adcx().expected_single_argument(list.span);
return None;
};
let single = cx.expect_single(list)?;
let Some(single) = single.meta_item() else {
cx.adcx().expected_name_value(single.span(), Some(sym::expected));
return None;
@@ -102,7 +100,6 @@ pub(crate) struct ReexportTestHarnessMainParser;
impl<S: Stage> SingleAttributeParser<S> for ReexportTestHarnessMainParser {
const PATH: &[Symbol] = &[sym::reexport_test_harness_main];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const TEMPLATE: AttributeTemplate = template!(NameValueStr: "name");
@@ -129,7 +126,6 @@ pub(crate) struct RustcAbiParser;
impl<S: Stage> SingleAttributeParser<S> for RustcAbiParser {
const PATH: &[Symbol] = &[sym::rustc_abi];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const TEMPLATE: AttributeTemplate = template!(OneOf: &[sym::debug, sym::assert_eq]);
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::TyAlias),
@@ -142,17 +138,13 @@ impl<S: Stage> SingleAttributeParser<S> for RustcAbiParser {
]);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(args) = args.list() else {
let Some(args) = args.as_list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_specific_argument_and_list(attr_span, &[sym::assert_eq, sym::debug]);
return None;
};
let Some(arg) = args.single() else {
let attr_span = cx.attr_span;
cx.adcx().expected_single_argument(attr_span);
return None;
};
let arg = cx.expect_single(args)?;
let mut fail_incorrect_argument =
|span| cx.adcx().expected_specific_argument(span, &[sym::assert_eq, sym::debug]);
@@ -179,7 +171,6 @@ pub(crate) struct RustcDelayedBugFromInsideQueryParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDelayedBugFromInsideQueryParser {
const PATH: &[Symbol] = &[sym::rustc_delayed_bug_from_inside_query];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcDelayedBugFromInsideQuery;
}
@@ -188,7 +179,6 @@ pub(crate) struct RustcEvaluateWhereClausesParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcEvaluateWhereClausesParser {
const PATH: &[Symbol] = &[sym::rustc_evaluate_where_clauses];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Fn),
Allow(Target::Method(MethodKind::Inherent)),
@@ -203,21 +193,11 @@ pub(crate) struct TestRunnerParser;
impl<S: Stage> SingleAttributeParser<S> for TestRunnerParser {
const PATH: &[Symbol] = &[sym::test_runner];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
const TEMPLATE: AttributeTemplate = template!(List: &["path"]);
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let Some(list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let Some(single) = list.single() else {
cx.adcx().expected_single_argument(list.span);
return None;
};
let single = cx.expect_single_element_list(args, cx.attr_span)?;
let Some(meta) = single.meta_item() else {
cx.adcx().expected_not_literal(single.span());
@@ -232,7 +212,6 @@ pub(crate) struct RustcTestMarkerParser;
impl<S: Stage> SingleAttributeParser<S> for RustcTestMarkerParser {
const PATH: &[Symbol] = &[sym::rustc_test_marker];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Const),
Allow(Target::Fn),

View File

@@ -1,16 +1,15 @@
use std::mem;
use super::prelude::*;
use crate::attributes::{NoArgsAttributeParser, OnDuplicate, SingleAttributeParser};
use crate::attributes::{NoArgsAttributeParser, SingleAttributeParser};
use crate::context::{AcceptContext, Stage};
use crate::parser::ArgParser;
use crate::target_checking::AllowedTargets;
use crate::target_checking::Policy::{Allow, Warn};
use crate::target_checking::{ALL_TARGETS, AllowedTargets};
pub(crate) struct RustcSkipDuringMethodDispatchParser;
impl<S: Stage> SingleAttributeParser<S> for RustcSkipDuringMethodDispatchParser {
const PATH: &[Symbol] = &[sym::rustc_skip_during_method_dispatch];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]);
const TEMPLATE: AttributeTemplate = template!(List: &["array, boxed_slice"]);
@@ -18,11 +17,7 @@ impl<S: Stage> SingleAttributeParser<S> for RustcSkipDuringMethodDispatchParser
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
let mut array = false;
let mut boxed_slice = false;
let Some(args) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let args = cx.expect_list(args, cx.attr_span)?;
if args.is_empty() {
cx.adcx().expected_at_least_one_argument(args.span);
return None;
@@ -60,7 +55,6 @@ impl<S: Stage> SingleAttributeParser<S> for RustcSkipDuringMethodDispatchParser
pub(crate) struct RustcParenSugarParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcParenSugarParser {
const PATH: &[Symbol] = &[sym::rustc_paren_sugar];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcParenSugar;
}
@@ -70,7 +64,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for RustcParenSugarParser {
pub(crate) struct MarkerParser;
impl<S: Stage> NoArgsAttributeParser<S> for MarkerParser {
const PATH: &[Symbol] = &[sym::marker];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
Allow(Target::Trait),
Warn(Target::Field),
@@ -83,7 +76,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for MarkerParser {
pub(crate) struct RustcDenyExplicitImplParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDenyExplicitImplParser {
const PATH: &[Symbol] = &[sym::rustc_deny_explicit_impl];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcDenyExplicitImpl;
}
@@ -91,7 +83,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for RustcDenyExplicitImplParser {
pub(crate) struct RustcDynIncompatibleTraitParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcDynIncompatibleTraitParser {
const PATH: &[Symbol] = &[sym::rustc_dyn_incompatible_trait];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcDynIncompatibleTrait;
}
@@ -101,7 +92,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for RustcDynIncompatibleTraitParser {
pub(crate) struct RustcSpecializationTraitParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcSpecializationTraitParser {
const PATH: &[Symbol] = &[sym::rustc_specialization_trait];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcSpecializationTrait;
}
@@ -109,7 +99,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for RustcSpecializationTraitParser {
pub(crate) struct RustcUnsafeSpecializationMarkerParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcUnsafeSpecializationMarkerParser {
const PATH: &[Symbol] = &[sym::rustc_unsafe_specialization_marker];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcUnsafeSpecializationMarker;
}
@@ -119,7 +108,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for RustcUnsafeSpecializationMarkerParse
pub(crate) struct RustcCoinductiveParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcCoinductiveParser {
const PATH: &[Symbol] = &[sym::rustc_coinductive];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Trait)]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcCoinductive;
}
@@ -127,7 +115,6 @@ impl<S: Stage> NoArgsAttributeParser<S> for RustcCoinductiveParser {
pub(crate) struct RustcAllowIncoherentImplParser;
impl<S: Stage> NoArgsAttributeParser<S> for RustcAllowIncoherentImplParser {
const PATH: &[Symbol] = &[sym::rustc_allow_incoherent_impl];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::Method(MethodKind::Inherent))]);
const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcAllowIncoherentImpl;
@@ -136,16 +123,7 @@ impl<S: Stage> NoArgsAttributeParser<S> for RustcAllowIncoherentImplParser {
pub(crate) struct FundamentalParser;
impl<S: Stage> NoArgsAttributeParser<S> for FundamentalParser {
const PATH: &[Symbol] = &[sym::fundamental];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets =
AllowedTargets::AllowList(&[Allow(Target::Struct), Allow(Target::Trait)]);
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::Fundamental;
}
pub(crate) struct PointeeParser;
impl<S: Stage> NoArgsAttributeParser<S> for PointeeParser {
const PATH: &[Symbol] = &[sym::pointee];
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS); //FIXME Still checked fully in `check_attr.rs`
const CREATE: fn(Span) -> AttributeKind = AttributeKind::Pointee;
}

View File

@@ -1,7 +1,6 @@
use std::num::IntErrorKind;
use rustc_ast::LitKind;
use rustc_ast::attr::AttributeExt;
use rustc_ast::{LitKind, ast};
use rustc_feature::is_builtin_attr_name;
use rustc_hir::RustcVersion;
use rustc_hir::limit::Limit;
@@ -27,8 +26,8 @@ pub fn parse_version(s: Symbol) -> Option<RustcVersion> {
Some(RustcVersion { major, minor, patch })
}
pub fn is_builtin_attr(attr: &impl AttributeExt) -> bool {
attr.is_doc_comment().is_some() || attr.name().is_some_and(|name| is_builtin_attr_name(name))
pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
attr.is_doc_comment() || attr.name().is_some_and(|name| is_builtin_attr_name(name))
}
/// Parse a single integer.
@@ -41,15 +40,7 @@ pub(crate) fn parse_single_integer<S: Stage>(
cx: &mut AcceptContext<'_, '_, S>,
args: &ArgParser,
) -> Option<u128> {
let Some(list) = args.list() else {
let attr_span = cx.attr_span;
cx.adcx().expected_list(attr_span, args);
return None;
};
let Some(single) = list.single() else {
cx.adcx().expected_single_argument(list.span);
return None;
};
let single = cx.expect_single_element_list(args, cx.attr_span)?;
let Some(lit) = single.lit() else {
cx.adcx().expected_integer_literal(single.span());
return None;

View File

@@ -7,7 +7,8 @@ use std::sync::LazyLock;
use private::Sealed;
use rustc_ast::{AttrStyle, MetaItemLit, NodeId};
use rustc_errors::{Diag, Diagnostic, Level, MultiSpan};
use rustc_data_structures::sync::{DynSend, DynSync};
use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan};
use rustc_feature::{AttrSuggestionStyle, AttributeTemplate};
use rustc_hir::attrs::AttributeKind;
use rustc_hir::lints::AttributeLintKind;
@@ -17,7 +18,6 @@ use rustc_session::Session;
use rustc_session::lint::{Lint, LintId};
use rustc_span::{ErrorGuaranteed, Span, Symbol};
use crate::AttributeParser;
// Glob imports to avoid big, bitrotty import lists
use crate::attributes::allow_unstable::*;
use crate::attributes::autodiff::*;
@@ -33,6 +33,7 @@ use crate::attributes::diagnostic::on_const::*;
use crate::attributes::diagnostic::on_move::*;
use crate::attributes::diagnostic::on_unimplemented::*;
use crate::attributes::diagnostic::on_unknown::*;
use crate::attributes::diagnostic::on_unmatch_args::*;
use crate::attributes::doc::*;
use crate::attributes::dummy::*;
use crate::attributes::inline::*;
@@ -59,13 +60,14 @@ use crate::attributes::stability::*;
use crate::attributes::test_attrs::*;
use crate::attributes::traits::*;
use crate::attributes::transparency::*;
use crate::attributes::{AttributeParser as _, Combine, Single, WithoutArgs};
use crate::parser::{ArgParser, RefPathParser};
use crate::attributes::{AttributeParser as _, AttributeSafety, Combine, Single, WithoutArgs};
use crate::parser::{ArgParser, MetaItemListParser, MetaItemOrLitParser, RefPathParser};
use crate::session_diagnostics::{
AttributeParseError, AttributeParseErrorReason, AttributeParseErrorSuggestions,
ParsedDescription,
};
use crate::target_checking::AllowedTargets;
use crate::{AttributeParser, EmitAttribute};
type GroupType<S> = LazyLock<GroupTypeInner<S>>;
pub(super) struct GroupTypeInner<S: Stage> {
@@ -76,13 +78,13 @@ pub(super) struct GroupTypeInnerAccept<S: Stage> {
pub(super) template: AttributeTemplate,
pub(super) accept_fn: AcceptFn<S>,
pub(super) allowed_targets: AllowedTargets,
pub(super) safety: AttributeSafety,
pub(super) finalizer: FinalizeFn<S>,
}
pub(crate) type AcceptFn<S> =
Box<dyn for<'sess, 'a> Fn(&mut AcceptContext<'_, 'sess, S>, &ArgParser) + Send + Sync>;
pub(crate) type FinalizeFn<S> =
Box<dyn Send + Sync + Fn(&mut FinalizeContext<'_, '_, S>) -> Option<AttributeKind>>;
pub(crate) type FinalizeFn<S> = fn(&mut FinalizeContext<'_, '_, S>) -> Option<AttributeKind>;
macro_rules! attribute_parsers {
(
@@ -126,11 +128,12 @@ macro_rules! attribute_parsers {
accept_fn(s, cx, args)
})
}),
safety: <$names as crate::attributes::AttributeParser<$stage>>::SAFETY,
allowed_targets: <$names as crate::attributes::AttributeParser<$stage>>::ALLOWED_TARGETS,
finalizer: Box::new(|cx| {
finalizer: |cx| {
let state = STATE_OBJECT.take();
state.finalize(cx)
})
}
});
}
Entry::Occupied(_) => panic!("Attribute {path:?} has multiple accepters"),
@@ -156,6 +159,7 @@ attribute_parsers!(
OnMoveParser,
OnUnimplementedParser,
OnUnknownParser,
OnUnmatchArgsParser,
RustcAlignParser,
RustcAlignStaticParser,
RustcCguTestAttributeParser,
@@ -179,6 +183,7 @@ attribute_parsers!(
Combine<RustcThenThisWouldNeedParser>,
Combine<TargetFeatureParser>,
Combine<UnstableFeatureBoundParser>,
Combine<UnstableRemovedParser>,
// tidy-alphabetical-end
// tidy-alphabetical-start
@@ -268,7 +273,6 @@ attribute_parsers!(
Single<WithoutArgs<PanicHandlerParser>>,
Single<WithoutArgs<PanicRuntimeParser>>,
Single<WithoutArgs<PinV2Parser>>,
Single<WithoutArgs<PointeeParser>>,
Single<WithoutArgs<PreludeImportParser>>,
Single<WithoutArgs<ProcMacroAttributeParser>>,
Single<WithoutArgs<ProcMacroParser>>,
@@ -314,6 +318,7 @@ attribute_parsers!(
Single<WithoutArgs<RustcNoImplicitAutorefsParser>>,
Single<WithoutArgs<RustcNoImplicitBoundsParser>>,
Single<WithoutArgs<RustcNoMirInlineParser>>,
Single<WithoutArgs<RustcNoWritableParser>>,
Single<WithoutArgs<RustcNonConstTraitMethodParser>>,
Single<WithoutArgs<RustcNonnullOptimizationGuaranteedParser>>,
Single<WithoutArgs<RustcNounwindParser>>,
@@ -458,11 +463,34 @@ impl<'f, 'sess: 'f, S: Stage> SharedContext<'f, 'sess, S> {
/// Emit a lint. This method is somewhat special, since lints emitted during attribute parsing
/// must be delayed until after HIR is built. This method will take care of the details of
/// that.
pub(crate) fn emit_lint<M: Into<MultiSpan>>(
pub(crate) fn emit_lint(
&mut self,
lint: &'static Lint,
kind: AttributeLintKind,
span: M,
span: impl Into<MultiSpan>,
) {
self.emit_lint_inner(lint, EmitAttribute::Static(kind), span);
}
/// Emit a lint. This method is somewhat special, since lints emitted during attribute parsing
/// must be delayed until after HIR is built. This method will take care of the details of
/// that.
pub(crate) fn emit_dyn_lint<
F: for<'a> Fn(DiagCtxtHandle<'a>, Level) -> Diag<'a, ()> + DynSend + DynSync + 'static,
>(
&mut self,
lint: &'static Lint,
callback: F,
span: impl Into<MultiSpan>,
) {
self.emit_lint_inner(lint, EmitAttribute::Dynamic(Box::new(callback)), span);
}
fn emit_lint_inner(
&mut self,
lint: &'static Lint,
kind: EmitAttribute,
span: impl Into<MultiSpan>,
) {
if !matches!(
self.stage.should_emit(),
@@ -474,12 +502,15 @@ impl<'f, 'sess: 'f, S: Stage> SharedContext<'f, 'sess, S> {
}
pub(crate) fn warn_unused_duplicate(&mut self, used_span: Span, unused_span: Span) {
self.emit_lint(
self.emit_dyn_lint(
rustc_session::lint::builtin::UNUSED_ATTRIBUTES,
AttributeLintKind::UnusedDuplicate {
this: unused_span,
other: used_span,
warning: false,
move |dcx, level| {
rustc_errors::lints::UnusedDuplicate {
this: unused_span,
other: used_span,
warning: false,
}
.into_diag(dcx, level)
},
unused_span,
)
@@ -490,12 +521,15 @@ impl<'f, 'sess: 'f, S: Stage> SharedContext<'f, 'sess, S> {
used_span: Span,
unused_span: Span,
) {
self.emit_lint(
self.emit_dyn_lint(
rustc_session::lint::builtin::UNUSED_ATTRIBUTES,
AttributeLintKind::UnusedDuplicate {
this: unused_span,
other: used_span,
warning: true,
move |dcx, level| {
rustc_errors::lints::UnusedDuplicate {
this: unused_span,
other: used_span,
warning: true,
}
.into_diag(dcx, level)
},
unused_span,
)
@@ -506,6 +540,82 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
pub(crate) fn adcx(&mut self) -> AttributeDiagnosticContext<'_, 'f, 'sess, S> {
AttributeDiagnosticContext { ctx: self, custom_suggestions: Vec::new() }
}
/// Asserts that this MetaItem is a list that contains a single element. Emits an error and
/// returns `None` if it is not the case.
///
/// Some examples:
///
/// - In `#[allow(warnings)]`, `warnings` is returned
/// - In `#[cfg_attr(docsrs, doc = "foo")]`, `None` is returned, "expected a single argument
/// here" is emitted.
/// - In `#[cfg()]`, `None` is returned, "expected an argument here" is emitted.
///
/// The provided span is used as a fallback for diagnostic generation in case `arg` does not
/// contain any. It should be the span of the node that contains `arg`.
pub(crate) fn expect_single_element_list<'arg>(
&mut self,
arg: &'arg ArgParser,
span: Span,
) -> Option<&'arg MetaItemOrLitParser> {
let ArgParser::List(l) = arg else {
self.adcx().expected_list(span, arg);
return None;
};
let Some(single) = l.as_single() else {
self.adcx().expected_single_argument(l.span, l.len());
return None;
};
Some(single)
}
/// Asserts that an [`ArgParser`] is a list and returns it, or emits an error and returns
/// `None`.
///
/// Some examples:
///
/// - `#[allow(clippy::complexity)]`: `(clippy::complexity)` is a list
/// - `#[rustfmt::skip::macros(target_macro_name)]`: `(target_macro_name)` is a list
///
/// This is a higher-level (and harder to misuse) wrapper over [`ArgParser::as_list`]. That
/// allows using `?` when the attribute parsing function allows it. You may still want to use
/// [`ArgParser::as_list`] for the following reasons:
///
/// - You want to emit your own diagnostics (for instance, with [`SharedContext::emit_err`]).
/// - The attribute can be parsed in multiple ways and it does not make sense to emit an error.
pub(crate) fn expect_list<'arg>(
&mut self,
args: &'arg ArgParser,
span: Span,
) -> Option<&'arg MetaItemListParser> {
let list = args.as_list();
if list.is_none() {
self.adcx().expected_list(span, args);
}
list
}
/// Asserts that a [`MetaItemListParser`] contains a single element and returns it, or emits an
/// error and returns `None`.
///
/// This is a higher-level (and harder to misuse) wrapper over [`MetaItemListParser::as_single`].
/// That allows using `?` to early return. You may still want to use
/// [`MetaItemListParser::as_single`] for the following reasons:
///
/// - You want to emit your own diagnostics (for instance, with [`SharedContext::emit_err`]).
/// - The attribute can be parsed in multiple ways and it does not make sense to emit an error.
pub(crate) fn expect_single<'arg>(
&mut self,
list: &'arg MetaItemListParser,
) -> Option<&'arg MetaItemOrLitParser> {
let single = list.as_single();
if single.is_none() {
self.adcx().expected_single_argument(list.span, list.len());
}
single
}
}
impl<'f, 'sess, S: Stage> Deref for AcceptContext<'f, 'sess, S> {
@@ -536,7 +646,7 @@ pub struct SharedContext<'p, 'sess, S: Stage> {
/// The second argument of the closure is a [`NodeId`] if `S` is `Early` and a [`HirId`] if `S`
/// is `Late` and is the ID of the syntactical component this attribute was applied to.
pub(crate) emit_lint: &'p mut dyn FnMut(LintId, MultiSpan, AttributeLintKind),
pub(crate) emit_lint: &'p mut dyn FnMut(LintId, MultiSpan, EmitAttribute),
}
/// Context given to every attribute parser during finalization.
@@ -693,6 +803,8 @@ where
)
}
/// The provided span is used as a fallback in case `args` does not contain any. It should be
/// the span of the node that contains `args`.
pub(crate) fn expected_list(&mut self, span: Span, args: &ArgParser) -> ErrorGuaranteed {
let span = match args {
ArgParser::NoArgs => span,
@@ -744,19 +856,38 @@ where
self.emit_parse_error(span, AttributeParseErrorReason::ExpectedNameValue(name))
}
/// Emit an error that a `name = value` argument is missing in a list of name-value pairs.
pub(crate) fn missing_name_value(&mut self, span: Span, name: Symbol) -> ErrorGuaranteed {
self.emit_parse_error(span, AttributeParseErrorReason::MissingNameValue(name))
}
/// Emit an error that a `name = value` pair was found where that name was already seen.
pub(crate) fn duplicate_key(&mut self, span: Span, key: Symbol) -> ErrorGuaranteed {
self.emit_parse_error(span, AttributeParseErrorReason::DuplicateKey(key))
}
/// An error that should be emitted when a [`MetaItemOrLitParser`](crate::parser::MetaItemOrLitParser)
/// An error that should be emitted when a [`MetaItemOrLitParser`]
/// was expected *not* to be a literal, but instead a meta item.
pub(crate) fn expected_not_literal(&mut self, span: Span) -> ErrorGuaranteed {
self.emit_parse_error(span, AttributeParseErrorReason::ExpectedNotLiteral)
}
pub(crate) fn expected_single_argument(&mut self, span: Span) -> ErrorGuaranteed {
self.emit_parse_error(span, AttributeParseErrorReason::ExpectedSingleArgument)
/// Signals that we expected exactly one argument and that we got either zero or two or more.
/// The `provided_arguments` argument allows distinguishing between "expected an argument here"
/// (when zero arguments are provided) and "expect a single argument here" (when two or more
/// arguments are provided).
pub(crate) fn expected_single_argument(
&mut self,
span: Span,
provided_arguments: usize,
) -> ErrorGuaranteed {
let reason = if provided_arguments == 0 {
AttributeParseErrorReason::ExpectedArgument
} else {
AttributeParseErrorReason::ExpectedSingleArgument
};
self.emit_parse_error(span, reason)
}
pub(crate) fn expected_at_least_one_argument(&mut self, span: Span) -> ErrorGuaranteed {
@@ -813,11 +944,18 @@ where
}
pub(crate) fn warn_empty_attribute(&mut self, span: Span) {
let attr_path = self.attr_path.clone().to_string();
let attr_path = self.attr_path.to_string();
let valid_without_list = self.template.word;
self.emit_lint(
self.emit_dyn_lint(
rustc_session::lint::builtin::UNUSED_ATTRIBUTES,
AttributeLintKind::EmptyAttribute { first_span: span, attr_path, valid_without_list },
move |dcx, level| {
crate::errors::EmptyAttributeList {
attr_span: span,
attr_path: &attr_path,
valid_without_list,
}
.into_diag(dcx, level)
},
span,
);
}
@@ -832,9 +970,12 @@ where
) {
let suggestions = self.suggestions();
let span = self.attr_span;
self.emit_lint(
self.emit_dyn_lint(
lint,
AttributeLintKind::IllFormedAttributeInput { suggestions, docs: None, help },
move |dcx, level| {
crate::errors::IllFormedAttributeInput::new(&suggestions, None, help.as_deref())
.into_diag(dcx, level)
},
span,
);
}

View File

@@ -1,4 +1,4 @@
use rustc_errors::MultiSpan;
use rustc_errors::{Applicability, DiagArgValue, MultiSpan};
use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::{Span, Symbol};
@@ -50,3 +50,374 @@ pub(crate) struct UnreachableCfgSelectPredicateWildcard {
#[label("always matches")]
pub wildcard_span: Span,
}
#[derive(Diagnostic)]
#[diag("must be a name of an associated function")]
pub(crate) struct MustBeNameOfAssociatedFunction {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
#[diag("unsafe attribute used without unsafe")]
pub(crate) struct UnsafeAttrOutsideUnsafeLint {
#[label("usage of unsafe attribute")]
pub span: Span,
#[subdiagnostic]
pub suggestion: Option<crate::session_diagnostics::UnsafeAttrOutsideUnsafeSuggestion>,
}
#[derive(Diagnostic)]
#[diag(
"{$num_suggestions ->
[1] attribute must be of the form {$suggestions}
*[other] valid forms for the attribute are {$suggestions}
}"
)]
pub(crate) struct IllFormedAttributeInput {
pub num_suggestions: usize,
pub suggestions: DiagArgValue,
#[note("for more information, visit <{$docs}>")]
pub has_docs: bool,
pub docs: &'static str,
#[subdiagnostic]
help: Option<IllFormedAttributeInputHelp>,
}
impl IllFormedAttributeInput {
pub(crate) fn new(
suggestions: &[String],
docs: Option<&'static str>,
help: Option<&str>,
) -> Self {
Self {
num_suggestions: suggestions.len(),
suggestions: DiagArgValue::StrListSepByAnd(
suggestions.into_iter().map(|s| format!("`{s}`").into()).collect(),
),
has_docs: docs.is_some(),
docs: docs.unwrap_or(""),
help: help.map(|h| IllFormedAttributeInputHelp { lint: h.to_string() }),
}
}
}
#[derive(Subdiagnostic)]
#[help(
"if you meant to silence a warning, consider using #![allow({$lint})] or #![expect({$lint})]"
)]
struct IllFormedAttributeInputHelp {
pub lint: String,
}
#[derive(Diagnostic)]
#[diag("unused attribute")]
#[note(
"{$valid_without_list ->
[true] using `{$attr_path}` with an empty list is equivalent to not using a list at all
*[other] using `{$attr_path}` with an empty list has no effect
}"
)]
pub(crate) struct EmptyAttributeList<'a> {
#[suggestion(
"{$valid_without_list ->
[true] remove these parentheses
*[other] remove this attribute
}",
code = "",
applicability = "machine-applicable"
)]
pub attr_span: Span,
pub attr_path: &'a str,
pub valid_without_list: bool,
}
#[derive(Diagnostic)]
#[diag("`#[{$name}]` attribute cannot be used on {$target}")]
#[warning(
"this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!"
)]
#[help("`#[{$name}]` can {$only}be applied to {$applied}")]
pub(crate) struct InvalidTargetLint {
pub name: String,
pub target: &'static str,
pub applied: DiagArgValue,
pub only: &'static str,
#[suggestion(
"remove the attribute",
code = "",
applicability = "machine-applicable",
style = "tool-only"
)]
pub attr_span: Span,
}
#[derive(Diagnostic)]
#[diag(
"{$is_used_as_inner ->
[false] crate-level attribute should be an inner attribute: add an exclamation mark: `#![{$name}]`
*[other] the `#![{$name}]` attribute can only be used at the crate root
}"
)]
pub(crate) struct InvalidAttrStyle<'a> {
pub name: &'a str,
pub is_used_as_inner: bool,
#[note("this attribute does not have an `!`, which means it is applied to this {$target}")]
pub target_span: Option<Span>,
pub target: &'static str,
}
#[derive(Diagnostic)]
#[diag("doc alias is duplicated")]
pub(crate) struct DocAliasDuplicated {
#[label("first defined here")]
pub first_definition: Span,
}
#[derive(Diagnostic)]
#[diag("only `hide` or `show` are allowed in `#[doc(auto_cfg(...))]`")]
pub(crate) struct DocAutoCfgExpectsHideOrShow;
#[derive(Diagnostic)]
#[diag("there exists a built-in attribute with the same name")]
pub(crate) struct AmbiguousDeriveHelpers;
#[derive(Diagnostic)]
#[diag("`#![doc(auto_cfg({$attr_name}(...)))]` only accepts identifiers or key/value items")]
pub(crate) struct DocAutoCfgHideShowUnexpectedItem {
pub attr_name: Symbol,
}
#[derive(Diagnostic)]
#[diag("`#![doc(auto_cfg({$attr_name}(...)))]` expects a list of items")]
pub(crate) struct DocAutoCfgHideShowExpectsList {
pub attr_name: Symbol,
}
#[derive(Diagnostic)]
#[diag("unknown `doc` attribute `include`")]
pub(crate) struct DocUnknownInclude {
pub inner: &'static str,
pub value: Symbol,
#[suggestion(
"use `doc = include_str!` instead",
code = "#{inner}[doc = include_str!(\"{value}\")]"
)]
pub sugg: (Span, Applicability),
}
#[derive(Diagnostic)]
#[diag("unknown `doc` attribute `spotlight`")]
#[note("`doc(spotlight)` was renamed to `doc(notable_trait)`")]
#[note("`doc(spotlight)` is now a no-op")]
pub(crate) struct DocUnknownSpotlight {
#[suggestion(
"use `notable_trait` instead",
style = "short",
applicability = "machine-applicable",
code = "notable_trait"
)]
pub sugg_span: Span,
}
#[derive(Diagnostic)]
#[diag("unknown `doc` attribute `{$name}`")]
#[note(
"`doc` attribute `{$name}` no longer functions; see issue #44136 <https://github.com/rust-lang/rust/issues/44136>"
)]
#[note("`doc({$name})` is now a no-op")]
pub(crate) struct DocUnknownPasses {
pub name: Symbol,
#[label("no longer functions")]
pub note_span: Span,
}
#[derive(Diagnostic)]
#[diag("unknown `doc` attribute `plugins`")]
#[note(
"`doc` attribute `plugins` no longer functions; see issue #44136 <https://github.com/rust-lang/rust/issues/44136> and CVE-2018-1000622 <https://nvd.nist.gov/vuln/detail/CVE-2018-1000622>"
)]
#[note("`doc(plugins)` is now a no-op")]
pub(crate) struct DocUnknownPlugins {
#[label("no longer functions")]
pub label_span: Span,
}
#[derive(Diagnostic)]
#[diag("unknown `doc` attribute `{$name}`")]
pub(crate) struct DocUnknownAny {
pub name: Symbol,
}
#[derive(Diagnostic)]
#[diag("expected boolean for `#[doc(auto_cfg = ...)]`")]
pub(crate) struct DocAutoCfgWrongLiteral;
#[derive(Diagnostic)]
#[diag("`#[doc(test(...)]` takes a list of attributes")]
pub(crate) struct DocTestTakesList;
#[derive(Diagnostic)]
#[diag("unknown `doc(test)` attribute `{$name}`")]
pub(crate) struct DocTestUnknown {
pub name: Symbol,
}
#[derive(Diagnostic)]
#[diag("`#![doc(test(...)]` does not take a literal")]
pub(crate) struct DocTestLiteral;
#[derive(Diagnostic)]
#[diag("this attribute can only be applied at the crate level")]
#[note(
"read <https://doc.rust-lang.org/nightly/rustdoc/the-doc-attribute.html#at-the-crate-level> for more information"
)]
pub(crate) struct AttrCrateLevelOnly;
#[derive(Diagnostic)]
#[diag("`#[diagnostic::do_not_recommend]` does not expect any arguments")]
pub(crate) struct DoNotRecommendDoesNotExpectArgs;
#[derive(Diagnostic)]
#[diag("invalid `crate_type` value")]
pub(crate) struct UnknownCrateTypes {
#[subdiagnostic]
pub sugg: Option<UnknownCrateTypesSuggestion>,
}
#[derive(Subdiagnostic)]
#[suggestion("did you mean", code = r#""{snippet}""#, applicability = "maybe-incorrect")]
pub(crate) struct UnknownCrateTypesSuggestion {
#[primary_span]
pub span: Span,
pub snippet: Symbol,
}
#[derive(Diagnostic)]
#[diag("`#[diagnostic::on_const]` can only be applied to non-const trait implementations")]
pub(crate) struct DiagnosticOnConstOnlyForTraitImpls {
#[label("not a trait implementation")]
pub target_span: Span,
}
#[derive(Diagnostic)]
#[diag("`#[diagnostic::on_move]` can only be applied to enums, structs or unions")]
pub(crate) struct DiagnosticOnMoveOnlyForAdt;
#[derive(Diagnostic)]
#[diag("`#[diagnostic::on_unimplemented]` can only be applied to trait definitions")]
pub(crate) struct DiagnosticOnUnimplementedOnlyForTraits;
#[derive(Diagnostic)]
#[diag("`#[diagnostic::on_unknown]` can only be applied to `use` statements")]
pub(crate) struct DiagnosticOnUnknownOnlyForImports {
#[label("not an import")]
pub target_span: Span,
}
#[derive(Diagnostic)]
#[diag("`#[diagnostic::on_unmatch_args]` can only be applied to macro definitions")]
pub(crate) struct DiagnosticOnUnmatchArgsOnlyForMacros;
#[derive(Diagnostic)]
#[diag("`#[diagnostic::do_not_recommend]` can only be placed on trait implementations")]
pub(crate) struct IncorrectDoNotRecommendLocation {
#[label("not a trait implementation")]
pub target_span: Span,
}
#[derive(Diagnostic)]
#[diag("malformed `doc` attribute input")]
#[warning(
"this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!"
)]
pub(crate) struct MalformedDoc;
#[derive(Diagnostic)]
#[diag("didn't expect any arguments here")]
#[warning(
"this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!"
)]
pub(crate) struct ExpectedNoArgs;
#[derive(Diagnostic)]
#[diag("expected this to be of the form `... = \"...\"`")]
#[warning(
"this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!"
)]
pub(crate) struct ExpectedNameValue;
#[derive(Diagnostic)]
#[diag("malformed `{$attribute}` attribute")]
#[help("{$options}")]
pub(crate) struct MalFormedDiagnosticAttributeLint {
pub attribute: &'static str,
pub options: &'static str,
#[label("invalid option found here")]
pub span: Span,
}
#[derive(Diagnostic)]
#[diag("{$description}")]
pub(crate) struct WrappedParserError<'a> {
pub description: &'a str,
#[label("{$label}")]
pub span: Span,
pub label: &'a str,
}
#[derive(Diagnostic)]
#[diag("`{$option_name}` is ignored due to previous definition of `{$option_name}`")]
pub(crate) struct IgnoredDiagnosticOption {
pub option_name: Symbol,
#[label("`{$option_name}` is first declared here")]
pub first_span: Span,
#[label("`{$option_name}` is later redundantly declared here")]
pub later_span: Span,
}
#[derive(Diagnostic)]
#[diag("missing options for `{$attribute}` attribute")]
#[help("{$options}")]
pub(crate) struct MissingOptionsForDiagnosticAttribute {
pub attribute: &'static str,
pub options: &'static str,
}
#[derive(Diagnostic)]
#[diag("expected a literal or missing delimiter")]
#[help(
"only literals are allowed as values for the `message`, `note` and `label` options. These options must be separated by a comma"
)]
pub(crate) struct NonMetaItemDiagnosticAttribute;
#[derive(Diagnostic, Clone, Copy)]
pub(crate) enum FormatWarning {
#[diag("positional arguments are not permitted in diagnostic attributes")]
#[help("you can print empty braces by escaping them")]
PositionalArgument {
#[label("remove this format argument")]
span: Span,
},
#[diag("indexed format arguments are not permitted in diagnostic attributes")]
IndexedArgument {
#[label("remove this format argument")]
span: Span,
},
#[diag("format specifiers are not permitted in diagnostic attributes")]
InvalidSpecifier {
#[label("remove this format specifier")]
span: Span,
},
#[diag("this format argument is not allowed in `#[{$attr}]`")]
#[note("{$allowed}")]
DisallowedPlaceholder {
#[label("remove this format argument")]
span: Span,
attr: &'static str,
allowed: &'static str,
},
}

View File

@@ -2,8 +2,9 @@ use std::convert::identity;
use rustc_ast as ast;
use rustc_ast::token::DocFragmentKind;
use rustc_ast::{AttrItemKind, AttrStyle, NodeId, Safety};
use rustc_errors::{DiagCtxtHandle, MultiSpan};
use rustc_ast::{AttrItemKind, AttrStyle, CRATE_NODE_ID, NodeId, Safety};
use rustc_data_structures::sync::{DynSend, DynSync};
use rustc_errors::{Diag, DiagCtxtHandle, Level, MultiSpan};
use rustc_feature::{AttributeTemplate, Features};
use rustc_hir::attrs::AttributeKind;
use rustc_hir::lints::AttributeLintKind;
@@ -12,12 +13,22 @@ use rustc_session::Session;
use rustc_session::lint::LintId;
use rustc_span::{DUMMY_SP, Span, Symbol, sym};
use crate::attributes::AttributeSafety;
use crate::context::{AcceptContext, FinalizeContext, FinalizeFn, SharedContext, Stage};
use crate::early_parsed::{EARLY_PARSED_ATTRIBUTES, EarlyParsedState};
use crate::parser::{AllowExprMetavar, ArgParser, PathParser, RefPathParser};
use crate::session_diagnostics::ParsedDescription;
use crate::{Early, Late, OmitDoc, ShouldEmit};
pub enum EmitAttribute {
Static(AttributeLintKind),
Dynamic(
Box<
dyn for<'a> Fn(DiagCtxtHandle<'a>, Level) -> Diag<'a, ()> + DynSend + DynSync + 'static,
>,
),
}
/// Context created once, for example as part of the ast lowering
/// context, through which all attributes can be lowered.
pub struct AttributeParser<'sess, S: Stage = Late> {
@@ -51,18 +62,16 @@ impl<'sess> AttributeParser<'sess, Early> {
sess: &'sess Session,
attrs: &[ast::Attribute],
sym: &'static [Symbol],
target_span: Span,
target_node_id: NodeId,
features: Option<&'sess Features>,
) -> Option<Attribute> {
Self::parse_limited_should_emit(
sess,
attrs,
sym,
target_span,
target_node_id,
Target::Crate, // Does not matter, we're not going to emit errors anyways
features,
// Because we're not emitting warnings/errors, the target should not matter
DUMMY_SP,
CRATE_NODE_ID,
Target::Crate,
None,
ShouldEmit::Nothing,
)
}
@@ -118,7 +127,14 @@ impl<'sess> AttributeParser<'sess, Early> {
target,
OmitDoc::Skip,
std::convert::identity,
|lint_id, span, kind| sess.psess.buffer_lint(lint_id.lint, span, target_node_id, kind),
|lint_id, span, kind| match kind {
EmitAttribute::Static(kind) => {
sess.psess.buffer_lint(lint_id.lint, span, target_node_id, kind)
}
EmitAttribute::Dynamic(callback) => {
sess.psess.dyn_buffer_lint(lint_id.lint, span, target_node_id, callback)
}
},
)
}
@@ -135,6 +151,7 @@ impl<'sess> AttributeParser<'sess, Early> {
parse_fn: fn(cx: &mut AcceptContext<'_, '_, Early>, item: &ArgParser) -> Option<T>,
template: &AttributeTemplate,
allow_expr_metavar: AllowExprMetavar,
expected_safety: AttributeSafety,
) -> Option<T> {
let ast::AttrKind::Normal(normal_attr) = &attr.kind else {
panic!("parse_single called on a doc attr")
@@ -157,6 +174,7 @@ impl<'sess> AttributeParser<'sess, Early> {
attr.style,
path,
Some(normal_attr.item.unsafety),
expected_safety,
ParsedDescription::Attribute,
target_span,
target_node_id,
@@ -178,6 +196,7 @@ impl<'sess> AttributeParser<'sess, Early> {
attr_style: AttrStyle,
attr_path: AttrPath,
attr_safety: Option<Safety>,
expected_safety: AttributeSafety,
parsed_description: ParsedDescription,
target_span: Span,
target_node_id: NodeId,
@@ -195,11 +214,22 @@ impl<'sess> AttributeParser<'sess, Early> {
sess,
stage: Early { emit_errors },
};
let mut emit_lint = |lint_id: LintId, span: MultiSpan, kind: AttributeLintKind| {
sess.psess.buffer_lint(lint_id.lint, span, target_node_id, kind)
let mut emit_lint = |lint_id: LintId, span: MultiSpan, kind: EmitAttribute| match kind {
EmitAttribute::Static(kind) => {
sess.psess.buffer_lint(lint_id.lint, span, target_node_id, kind)
}
EmitAttribute::Dynamic(callback) => {
sess.psess.dyn_buffer_lint(lint_id.lint, span, target_node_id, callback)
}
};
if let Some(safety) = attr_safety {
parser.check_attribute_safety(&attr_path, inner_span, safety, &mut emit_lint)
parser.check_attribute_safety(
&attr_path,
inner_span,
safety,
expected_safety,
&mut emit_lint,
);
}
let mut cx: AcceptContext<'_, 'sess, Early> = AcceptContext {
shared: SharedContext {
@@ -256,7 +286,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
target: Target,
omit_doc: OmitDoc,
lower_span: impl Copy + Fn(Span) -> Span,
mut emit_lint: impl FnMut(LintId, MultiSpan, AttributeLintKind),
mut emit_lint: impl FnMut(LintId, MultiSpan, EmitAttribute),
) -> Vec<Attribute> {
let mut attributes = Vec::new();
// We store the attributes we intend to discard at the end of this function in order to
@@ -267,7 +297,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
let mut attr_paths: Vec<RefPathParser<'_>> = Vec::new();
let mut early_parsed_state = EarlyParsedState::default();
let mut finalizers: Vec<&FinalizeFn<S>> = Vec::with_capacity(attrs.len());
let mut finalizers: Vec<FinalizeFn<S>> = Vec::with_capacity(attrs.len());
for attr in attrs {
// If we're only looking for a single attribute, skip all the ones we don't care about.
@@ -314,17 +344,18 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
}
};
self.check_attribute_safety(
&attr_path,
lower_span(n.item.span()),
n.item.unsafety,
&mut emit_lint,
);
let parts =
n.item.path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>();
if let Some(accept) = S::parsers().accepters.get(parts.as_slice()) {
self.check_attribute_safety(
&attr_path,
lower_span(n.item.span()),
n.item.unsafety,
accept.safety,
&mut emit_lint,
);
let Some(args) = ArgParser::from_attr_args(
args,
&parts,
@@ -382,7 +413,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
};
(accept.accept_fn)(&mut cx, &args);
finalizers.push(&accept.finalizer);
finalizers.push(accept.finalizer);
if !matches!(cx.stage.should_emit(), ShouldEmit::Nothing) {
Self::check_target(&accept.allowed_targets, target, &mut cx);
@@ -397,6 +428,14 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
span: attr_span,
};
self.check_attribute_safety(
&attr_path,
lower_span(n.item.span()),
n.item.unsafety,
AttributeSafety::Normal,
&mut emit_lint,
);
if !matches!(self.stage.should_emit(), ShouldEmit::Nothing)
&& target == Target::Crate
{

View File

@@ -106,11 +106,12 @@ mod session_diagnostics;
mod target_checking;
pub mod validate_attr;
pub use attributes::AttributeSafety;
pub use attributes::cfg::{
CFG_TEMPLATE, EvalConfigResult, eval_config_entry, parse_cfg, parse_cfg_attr, parse_cfg_entry,
};
pub use attributes::cfg_select::*;
pub use attributes::util::{is_builtin_attr, parse_version};
pub use context::{Early, Late, OmitDoc, ShouldEmit};
pub use interface::AttributeParser;
pub use interface::{AttributeParser, EmitAttribute};
pub use session_diagnostics::ParsedDescription;

View File

@@ -176,7 +176,7 @@ impl ArgParser {
///
/// - `#[allow(clippy::complexity)]`: `(clippy::complexity)` is a list
/// - `#[rustfmt::skip::macros(target_macro_name)]`: `(target_macro_name)` is a list
pub fn list(&self) -> Option<&MetaItemListParser> {
pub fn as_list(&self) -> Option<&MetaItemListParser> {
match self {
Self::List(l) => Some(l),
Self::NameValue(_) | Self::NoArgs => None,
@@ -255,6 +255,7 @@ impl MetaItemOrLitParser {
}
}
// FIXME(scrabsha): once #155696 is merged, update this and mention the higher-level APIs.
/// Utility that deconstructs a MetaItem into usable parts.
///
/// MetaItems are syntactically extremely flexible, but specific attributes want to parse
@@ -263,7 +264,7 @@ impl MetaItemOrLitParser {
/// MetaItems consist of some path, and some args. The args could be empty. In other words:
///
/// - `name` -> args are empty
/// - `name(...)` -> args are a [`list`](ArgParser::list), which is the bit between the parentheses
/// - `name(...)` -> args are a [`list`](ArgParser::as_list), which is the bit between the parentheses
/// - `name = value`-> arg is [`name_value`](ArgParser::name_value), where the argument is the
/// `= value` part
///
@@ -694,7 +695,7 @@ impl MetaItemListParser {
/// Returns Some if the list contains only a single element.
///
/// Inside the Some is the parser to parse this single element.
pub fn single(&self) -> Option<&MetaItemOrLitParser> {
pub fn as_single(&self) -> Option<&MetaItemOrLitParser> {
let mut iter = self.mixed();
iter.next().filter(|_| iter.next().is_none())
}

View File

@@ -1,14 +1,13 @@
use rustc_ast::Safety;
use rustc_errors::MultiSpan;
use rustc_feature::{AttributeSafety, BUILTIN_ATTRIBUTE_MAP};
use rustc_errors::{Diagnostic, MultiSpan};
use rustc_hir::AttrPath;
use rustc_hir::lints::AttributeLintKind;
use rustc_session::lint::LintId;
use rustc_session::lint::builtin::UNSAFE_ATTR_OUTSIDE_UNSAFE;
use rustc_span::Span;
use crate::attributes::AttributeSafety;
use crate::context::Stage;
use crate::{AttributeParser, ShouldEmit};
use crate::{AttributeParser, EmitAttribute, ShouldEmit, errors};
impl<'sess, S: Stage> AttributeParser<'sess, S> {
pub fn check_attribute_safety(
@@ -16,28 +15,23 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
attr_path: &AttrPath,
attr_span: Span,
attr_safety: Safety,
emit_lint: &mut impl FnMut(LintId, MultiSpan, AttributeLintKind),
expected_safety: AttributeSafety,
emit_lint: &mut impl FnMut(LintId, MultiSpan, EmitAttribute),
) {
if matches!(self.stage.should_emit(), ShouldEmit::Nothing) {
return;
}
let name = (attr_path.segments.len() == 1).then_some(attr_path.segments[0]);
// FIXME: We should retrieve this information from the attribute parsers instead of from `BUILTIN_ATTRIBUTE_MAP`
let builtin_attr_info = name.and_then(|name| BUILTIN_ATTRIBUTE_MAP.get(&name));
let builtin_attr_safety = builtin_attr_info.map(|x| x.safety);
match (builtin_attr_safety, attr_safety) {
match (expected_safety, attr_safety) {
// - Unsafe builtin attribute
// - User wrote `#[unsafe(..)]`, which is permitted on any edition
(Some(AttributeSafety::Unsafe { .. }), Safety::Unsafe(..)) => {
(AttributeSafety::Unsafe { .. }, Safety::Unsafe(..)) => {
// OK
}
// - Unsafe builtin attribute
// - User did not write `#[unsafe(..)]`
(Some(AttributeSafety::Unsafe { unsafe_since }), Safety::Default) => {
(AttributeSafety::Unsafe { unsafe_since }, Safety::Default) => {
let path_span = attr_path.span;
// If the `attr_item`'s span is not from a macro, then just suggest
@@ -85,18 +79,24 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
emit_lint(
LintId::of(UNSAFE_ATTR_OUTSIDE_UNSAFE),
path_span.into(),
AttributeLintKind::UnsafeAttrOutsideUnsafe {
attribute_name_span: path_span,
sugg_spans: not_from_proc_macro
.then(|| (diag_span.shrink_to_lo(), diag_span.shrink_to_hi())),
},
EmitAttribute::Dynamic(Box::new(move |dcx, level| {
errors::UnsafeAttrOutsideUnsafeLint {
span: path_span,
suggestion: not_from_proc_macro
.then(|| (diag_span.shrink_to_lo(), diag_span.shrink_to_hi()))
.map(|(left, right)| {
crate::session_diagnostics::UnsafeAttrOutsideUnsafeSuggestion { left, right }
}),
}
.into_diag(dcx, level)
})),
)
}
}
// - Normal builtin attribute
// - Writing `#[unsafe(..)]` is not permitted on normal builtin attributes
(None | Some(AttributeSafety::Normal), Safety::Unsafe(unsafe_span)) => {
(AttributeSafety::Normal, Safety::Unsafe(unsafe_span)) => {
self.stage.emit_err(
self.sess,
crate::session_diagnostics::InvalidAttrUnsafe {
@@ -108,14 +108,11 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
// - Normal builtin attribute
// - No explicit `#[unsafe(..)]` written.
(None | Some(AttributeSafety::Normal), Safety::Default) => {
(AttributeSafety::Normal, Safety::Default) => {
// OK
}
(
Some(AttributeSafety::Unsafe { .. } | AttributeSafety::Normal) | None,
Safety::Safe(..),
) => {
(_, Safety::Safe(..)) => {
self.sess.dcx().span_delayed_bug(
attr_span,
"`check_attribute_safety` does not expect `Safety::Safe` on attributes",

View File

@@ -557,6 +557,7 @@ pub(crate) enum AttributeParseErrorReason<'a> {
upper_bound: isize,
},
ExpectedAtLeastOneArgument,
ExpectedArgument,
ExpectedSingleArgument,
ExpectedList,
ExpectedListOrNoArgs,
@@ -567,6 +568,7 @@ pub(crate) enum AttributeParseErrorReason<'a> {
ExpectedNonEmptyStringLiteral,
ExpectedNotLiteral,
ExpectedNameValue(Option<Symbol>),
MissingNameValue(Symbol),
DuplicateKey(Symbol),
ExpectedSpecificArgument {
possibilities: &'a [Symbol],
@@ -773,6 +775,10 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for AttributeParseError<'_> {
diag.span_label(self.span, "expected a single argument here");
diag.code(E0805);
}
AttributeParseErrorReason::ExpectedArgument => {
diag.span_label(self.span, "expected an argument here");
diag.code(E0805);
}
AttributeParseErrorReason::ExpectedAtLeastOneArgument => {
diag.span_label(self.span, "expected at least 1 argument here");
}
@@ -818,6 +824,9 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for AttributeParseError<'_> {
format!("expected this to be of the form `{name} = \"...\"`"),
);
}
AttributeParseErrorReason::MissingNameValue(name) => {
diag.span_label(self.span, format!("missing argument `{name} = \"...\"`"));
}
AttributeParseErrorReason::ExpectedSpecificArgument {
possibilities,
strings,
@@ -1128,3 +1137,22 @@ pub(crate) struct UnstableAttrForAlreadyStableFeature {
#[label("the stability attribute annotates this item")]
pub item_span: Span,
}
#[derive(Diagnostic)]
#[diag("invalid Mach-O section specifier")]
pub(crate) struct InvalidMachoSection {
#[primary_span]
#[label("not a valid Mach-O section specifier")]
pub name_span: Span,
#[subdiagnostic]
pub reason: InvalidMachoSectionReason,
}
#[derive(Subdiagnostic)]
pub(crate) enum InvalidMachoSectionReason {
#[note("a Mach-O section specifier requires a segment and a section, separated by a comma")]
#[help("an example of a valid Mach-O section specifier is `__TEXT,__cstring`")]
MissingSection,
#[note("section name `{$section}` is longer than 16 bytes")]
SectionTooLong { section: String },
}

View File

@@ -1,17 +1,17 @@
use std::borrow::Cow;
use rustc_ast::AttrStyle;
use rustc_errors::{DiagArgValue, MultiSpan, StashKey};
use rustc_errors::{DiagArgValue, Diagnostic, MultiSpan, StashKey};
use rustc_feature::Features;
use rustc_hir::attrs::AttributeKind;
use rustc_hir::lints::AttributeLintKind;
use rustc_hir::{AttrItem, Attribute, MethodKind, Target};
use rustc_span::{BytePos, Span, Symbol, sym};
use crate::AttributeParser;
use crate::context::{AcceptContext, Stage};
use crate::errors::{
InvalidAttrAtCrateLevel, ItemFollowingInnerAttr, UnsupportedAttributesInWhere,
InvalidAttrAtCrateLevel, InvalidTargetLint, ItemFollowingInnerAttr,
UnsupportedAttributesInWhere,
};
use crate::session_diagnostics::InvalidTarget;
use crate::target_checking::Policy::Allow;
@@ -142,14 +142,19 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
};
let attr_span = cx.attr_span;
cx.emit_lint(
cx.emit_dyn_lint(
lint,
AttributeLintKind::InvalidTarget {
name: name.to_string(),
target: target.plural_name(),
only: if only { "only " } else { "" },
applied,
attr_span,
move |dcx, level| {
InvalidTargetLint {
name: name.to_string(),
target: target.plural_name(),
only: if only { "only " } else { "" },
applied: DiagArgValue::StrListSepByAnd(
applied.iter().map(|i| Cow::Owned(i.to_string())).collect(),
),
attr_span,
}
.into_diag(dcx, level)
},
attr_span,
);
@@ -176,15 +181,24 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
return;
}
let kind = AttributeLintKind::InvalidStyle {
name: cx.attr_path.to_string(),
is_used_as_inner: cx.attr_style == AttrStyle::Inner,
target: target.name(),
target_span: cx.target_span,
};
let name = cx.attr_path.to_string();
let is_used_as_inner = cx.attr_style == AttrStyle::Inner;
let target_span = cx.target_span;
let attr_span = cx.attr_span;
cx.emit_lint(rustc_session::lint::builtin::UNUSED_ATTRIBUTES, kind, attr_span);
cx.emit_dyn_lint(
rustc_session::lint::builtin::UNUSED_ATTRIBUTES,
move |dcx, level| {
crate::errors::InvalidAttrStyle {
name: &name,
is_used_as_inner,
target_span: (!is_used_as_inner).then_some(target_span),
target: target.name(),
}
.into_diag(dcx, level)
},
attr_span,
);
}
// FIXME: Fix "Cannot determine resolution" error and remove built-in macros

View File

@@ -8,10 +8,9 @@ use rustc_ast::tokenstream::DelimSpan;
use rustc_ast::{
self as ast, AttrArgs, Attribute, DelimArgs, MetaItem, MetaItemInner, MetaItemKind, Safety,
};
use rustc_errors::{Applicability, FatalError, PResult};
use rustc_feature::{AttributeTemplate, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute};
use rustc_errors::{Applicability, Diagnostic, PResult};
use rustc_feature::{AttributeTemplate, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute, template};
use rustc_hir::AttrPath;
use rustc_hir::lints::AttributeLintKind;
use rustc_parse::parse_in;
use rustc_session::errors::report_lit_error;
use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT;
@@ -30,15 +29,22 @@ pub fn check_attr(psess: &ParseSess, attr: &Attribute) {
// Check input tokens for built-in and key-value attributes.
match builtin_attr_info {
// `rustc_dummy` doesn't have any restrictions specific to built-in attributes.
Some(BuiltinAttribute { name, template, .. }) => {
Some(BuiltinAttribute { name, .. }) => {
if AttributeParser::<Late>::is_parsed_attribute(slice::from_ref(&name)) {
return;
}
match parse_meta(psess, attr) {
// Don't check safety again, we just did that
Ok(meta) => {
check_builtin_meta_item(psess, &meta, attr.style, *name, *template, false)
// FIXME The only unparsed builtin attributes that are left are the lint attributes, so we can hardcode the template here
let lint_attrs = [sym::forbid, sym::allow, sym::warn, sym::deny, sym::expect];
assert!(lint_attrs.contains(name));
let template = template!(
List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
"https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
);
check_builtin_meta_item(psess, &meta, attr.style, *name, template, false)
}
Err(err) => {
err.emit();
@@ -169,7 +175,7 @@ pub fn check_builtin_meta_item(
}
}
fn emit_malformed_attribute(
pub fn emit_malformed_attribute(
psess: &ParseSess,
style: ast::AttrStyle,
span: Span,
@@ -203,14 +209,14 @@ fn emit_malformed_attribute(
suggestions.clear();
}
if should_warn(name) {
psess.buffer_lint(
let suggestions = suggestions.clone();
psess.dyn_buffer_lint(
ILL_FORMED_ATTRIBUTE_INPUT,
span,
ast::CRATE_NODE_ID,
AttributeLintKind::IllFormedAttributeInput {
suggestions: suggestions.clone(),
docs: template.docs,
help: None,
move |dcx, level| {
crate::errors::IllFormedAttributeInput::new(&suggestions, template.docs, None)
.into_diag(dcx, level)
},
);
} else {
@@ -231,15 +237,3 @@ fn emit_malformed_attribute(
err.emit();
}
}
pub fn emit_fatal_malformed_builtin_attribute(
psess: &ParseSess,
attr: &Attribute,
name: Symbol,
) -> ! {
let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template;
emit_malformed_attribute(psess, attr.style, attr.span, name, template);
// This is fatal, otherwise it will likely cause a cascade of other errors
// (and an error here is expected to be very rare).
FatalError.raise()
}

View File

@@ -14,7 +14,7 @@ use rustc_infer::traits::query::{
};
use rustc_middle::ty::error::TypeError;
use rustc_middle::ty::{
self, RePlaceholder, Region, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex,
self, RePlaceholder, Region, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex, Unnormalized,
};
use rustc_span::Span;
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
@@ -275,7 +275,7 @@ where
// the former fails to normalize the `nll/relate_tys/impl-fn-ignore-binder-via-bottom.rs`
// test. Check after #85499 lands to see if its fixes have erased this difference.
let ty::ParamEnvAnd { param_env, value } = key;
let _ = ocx.normalize(&cause, param_env, value.value);
let _ = ocx.normalize(&cause, param_env, Unnormalized::new_wip(value.value));
let diag = try_extract_error_from_fulfill_cx(
&ocx,
@@ -322,7 +322,7 @@ where
let ocx = ObligationCtxt::new(&infcx);
let ty::ParamEnvAnd { param_env, value } = key;
let _ = ocx.deeply_normalize(&cause, param_env, value.value);
let _ = ocx.deeply_normalize(&cause, param_env, Unnormalized::new_wip(value.value));
let diag = try_extract_error_from_fulfill_cx(
&ocx,
@@ -451,7 +451,7 @@ fn try_extract_error_from_region_constraints<'a, 'tcx>(
(RePlaceholder(a_p), RePlaceholder(b_p)) => a_p.bound == b_p.bound,
_ => a_region == b_region,
};
let mut check = |c: &Constraint<'tcx>, cause: &SubregionOrigin<'tcx>, exact| match c.kind {
let mut check = |c: Constraint<'tcx>, cause: &SubregionOrigin<'tcx>, exact| match c.kind {
ConstraintKind::RegSubReg
if ((exact && c.sup == placeholder_region)
|| (!exact && regions_the_same(c.sup, placeholder_region)))
@@ -467,13 +467,23 @@ fn try_extract_error_from_region_constraints<'a, 'tcx>(
{
Some((c.sub, cause.clone()))
}
_ => None,
ConstraintKind::VarSubVar
| ConstraintKind::RegSubVar
| ConstraintKind::VarSubReg
| ConstraintKind::RegSubReg => None,
ConstraintKind::VarEqVar | ConstraintKind::VarEqReg | ConstraintKind::RegEqReg => {
unreachable!()
}
};
let mut find_culprit = |exact_match: bool| {
region_constraints
.constraints
.iter()
.flat_map(|(constraint, cause)| {
constraint.iter_outlives().map(move |constraint| (constraint, cause))
})
.find_map(|(constraint, cause)| check(constraint, cause, exact_match))
};

View File

@@ -156,14 +156,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
.collect();
generic_args.push((kw::SelfUpper, this.clone()));
let args = FormatArgs {
this,
// Unused
this_sugared: String::new(),
// Unused
item_context: "",
generic_args,
};
let args = FormatArgs { this, generic_args, .. };
let CustomDiagnostic { message, label, notes, parent_label: _ } =
directive.eval(None, &args);
@@ -754,19 +747,19 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
// Test the callee's predicates, substituting in `ref_ty` for the moved argument type.
clauses.instantiate(tcx, new_args).predicates.iter().all(|&(mut clause)| {
clauses.instantiate(tcx, new_args).predicates.iter().all(|clause| {
// Normalize before testing to see through type aliases and projections.
if let Ok(normalized) = tcx.try_normalize_erasing_regions(
self.infcx.typing_env(self.infcx.param_env),
clause,
) {
clause = normalized;
}
let normalized = tcx
.try_normalize_erasing_regions(
self.infcx.typing_env(self.infcx.param_env),
*clause,
)
.unwrap_or_else(|_| clause.skip_norm_wip());
self.infcx.predicate_must_hold_modulo_regions(&Obligation::new(
tcx,
ObligationCause::dummy(),
self.infcx.param_env,
clause,
normalized,
))
})
}) {
@@ -4040,23 +4033,74 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if let Some(decl) = local_decl
&& decl.can_be_made_mutable()
{
let is_for_loop = matches!(
decl.local_info(),
LocalInfo::User(BindingForm::Var(VarBindingForm {
opt_match_place: Some((_, match_span)),
..
})) if matches!(match_span.desugaring_kind(), Some(DesugaringKind::ForLoop))
);
let message = if is_for_loop
let mut is_for_loop = false;
let mut is_ref_pattern = false;
if let LocalInfo::User(BindingForm::Var(VarBindingForm {
opt_match_place: Some((_, match_span)),
..
})) = *decl.local_info()
{
if matches!(match_span.desugaring_kind(), Some(DesugaringKind::ForLoop)) {
is_for_loop = true;
if let Some(body) = self.infcx.tcx.hir_maybe_body_owned_by(self.mir_def_id()) {
struct RefPatternFinder<'tcx> {
tcx: TyCtxt<'tcx>,
binding_span: Span,
is_ref_pattern: bool,
}
impl<'tcx> Visitor<'tcx> for RefPatternFinder<'tcx> {
type NestedFilter = OnlyBodies;
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
if !self.is_ref_pattern
&& let hir::PatKind::Binding(_, _, ident, _) = pat.kind
&& ident.span == self.binding_span
{
self.is_ref_pattern =
self.tcx.hir_parent_iter(pat.hir_id).any(|(_, node)| {
matches!(
node,
hir::Node::Pat(hir::Pat {
kind: hir::PatKind::Ref(..),
..
})
)
});
}
hir::intravisit::walk_pat(self, pat);
}
}
let mut finder = RefPatternFinder {
tcx: self.infcx.tcx,
binding_span: decl.source_info.span,
is_ref_pattern: false,
};
finder.visit_body(body);
is_ref_pattern = finder.is_ref_pattern;
}
}
}
let (span, message) = if is_for_loop
&& is_ref_pattern
&& let Ok(binding_name) =
self.infcx.tcx.sess.source_map().span_to_snippet(decl.source_info.span)
{
format!("(mut {}) ", binding_name)
(decl.source_info.span, format!("(mut {})", binding_name))
} else {
"mut ".to_string()
(decl.source_info.span.shrink_to_lo(), "mut ".to_string())
};
err.span_suggestion_verbose(
decl.source_info.span.shrink_to_lo(),
span,
"consider making this binding mutable",
message,
Applicability::MachineApplicable,
@@ -4171,11 +4215,20 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if is_closure {
None
} else {
let ty = self.infcx.tcx.type_of(self.mir_def_id()).instantiate_identity();
let ty = self
.infcx
.tcx
.type_of(self.mir_def_id())
.instantiate_identity()
.skip_norm_wip();
match ty.kind() {
ty::FnDef(_, _) | ty::FnPtr(..) => self.annotate_fn_sig(
self.mir_def_id(),
self.infcx.tcx.fn_sig(self.mir_def_id()).instantiate_identity(),
self.infcx
.tcx
.fn_sig(self.mir_def_id())
.instantiate_identity()
.skip_norm_wip(),
),
_ => None,
}

View File

@@ -602,8 +602,14 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
BorrowedContentSource::DerefRawPointer
} else if base_ty.is_mutable_ptr() {
BorrowedContentSource::DerefMutableRef
} else {
} else if base_ty.is_ref() {
BorrowedContentSource::DerefSharedRef
} else {
// Custom type implementing `Deref` (e.g. `MyBox<T>`, `Rc<T>`, `Arc<T>`)
// that wasn't detected via the MIR init trace above. This can happen
// when the deref base is initialized by a regular statement rather than
// a `TerminatorKind::Call` with `CallSource::OverloadedOperator`.
BorrowedContentSource::OverloadedDeref(base_ty)
}
}
@@ -1002,6 +1008,14 @@ struct CapturedMessageOpt {
maybe_reinitialized_locations_is_empty: bool,
}
/// Tracks whether [`MirBorrowckCtxt::explain_captures`] emitted a clone
/// suggestion, so callers can avoid emitting redundant suggestions downstream.
#[derive(Copy, Clone, PartialEq, Eq)]
pub(super) enum CloneSuggestion {
Emitted,
NotEmitted,
}
impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
/// Finds the spans associated to a move or copy of move_place at location.
pub(super) fn move_spans(
@@ -1226,7 +1240,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
move_spans: UseSpans<'tcx>,
moved_place: Place<'tcx>,
msg_opt: CapturedMessageOpt,
) {
) -> CloneSuggestion {
let CapturedMessageOpt {
is_partial_move: is_partial,
is_loop_message,
@@ -1235,6 +1249,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
has_suggest_reborrow,
maybe_reinitialized_locations_is_empty,
} = msg_opt;
let mut suggested_cloning = false;
if let UseSpans::FnSelfUse { var_span, fn_call_span, fn_span, kind } = move_spans {
let place_name = self
.describe_place(moved_place.as_ref())
@@ -1366,9 +1381,12 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let parent_self_ty =
matches!(tcx.def_kind(parent_did), rustc_hir::def::DefKind::Impl { .. })
.then_some(parent_did)
.and_then(|did| match tcx.type_of(did).instantiate_identity().kind() {
ty::Adt(def, ..) => Some(def.did()),
_ => None,
.and_then(|did| {
match tcx.type_of(did).instantiate_identity().skip_norm_wip().kind()
{
ty::Adt(def, ..) => Some(def.did()),
_ => None,
}
});
let is_option_or_result = parent_self_ty.is_some_and(|def_id| {
matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
@@ -1445,7 +1463,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
&& let self_ty = self.infcx.instantiate_binder_with_fresh_vars(
fn_call_span,
BoundRegionConversionTime::FnCall,
tcx.fn_sig(method_did).instantiate(tcx, method_args).input(0),
tcx.fn_sig(method_did)
.instantiate(tcx, method_args)
.skip_norm_wip()
.input(0),
)
&& self.infcx.can_eq(self.infcx.param_env, ty, self_ty)
{
@@ -1455,10 +1476,26 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
has_sugg = true;
}
if let Some(clone_trait) = tcx.lang_items().clone_trait() {
let sugg = if moved_place
// Check whether the deref is from a custom Deref impl
// (e.g. Rc, Box) or a built-in reference deref.
// For built-in derefs with Clone fully satisfied, we skip
// the UFCS suggestion here and let `suggest_cloning`
// downstream emit a simpler `.clone()` suggestion instead.
let has_overloaded_deref =
moved_place.iter_projections().any(|(place, elem)| {
matches!(elem, ProjectionElem::Deref)
&& matches!(
self.borrowed_content_source(place),
BorrowedContentSource::OverloadedDeref(_)
| BorrowedContentSource::OverloadedIndex(_)
)
});
let has_deref = moved_place
.iter_projections()
.any(|(_, elem)| matches!(elem, ProjectionElem::Deref))
{
.any(|(_, elem)| matches!(elem, ProjectionElem::Deref));
let sugg = if has_deref {
let (start, end) = if let Some(expr) = self.find_expr(move_span)
&& let Some(_) = self.clone_on_reference(expr)
&& let hir::ExprKind::MethodCall(_, rcvr, _, _) = expr.kind
@@ -1484,43 +1521,58 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
self.infcx.param_env,
) && !has_sugg
{
let msg = match &errors[..] {
[] => "you can `clone` the value and consume it, but this \
might not be your desired behavior"
.to_string(),
[error] => {
format!(
"you could `clone` the value and consume it, if the \
`{}` trait bound could be satisfied",
error.obligation.predicate,
)
}
_ => {
format!(
"you could `clone` the value and consume it, if the \
following trait bounds could be satisfied: {}",
listify(&errors, |e: &FulfillmentError<'tcx>| format!(
"`{}`",
e.obligation.predicate
))
.unwrap(),
)
}
};
err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
for error in errors {
if let FulfillmentErrorCode::Select(
SelectionError::Unimplemented,
) = error.code
&& let ty::PredicateKind::Clause(ty::ClauseKind::Trait(
pred,
)) = error.obligation.predicate.kind().skip_binder()
{
self.infcx.err_ctxt().suggest_derive(
&error.obligation,
err,
error.obligation.predicate.kind().rebind(pred),
);
let skip_for_simple_clone =
has_deref && !has_overloaded_deref && errors.is_empty();
if !skip_for_simple_clone {
let msg = match &errors[..] {
[] => "you can `clone` the value and consume it, but \
this might not be your desired behavior"
.to_string(),
[error] => {
format!(
"you could `clone` the value and consume it, if \
the `{}` trait bound could be satisfied",
error.obligation.predicate,
)
}
_ => {
format!(
"you could `clone` the value and consume it, if \
the following trait bounds could be satisfied: \
{}",
listify(
&errors,
|e: &FulfillmentError<'tcx>| format!(
"`{}`",
e.obligation.predicate
)
)
.unwrap(),
)
}
};
err.multipart_suggestion(
msg,
sugg,
Applicability::MaybeIncorrect,
);
suggested_cloning = errors.is_empty();
for error in errors {
if let FulfillmentErrorCode::Select(
SelectionError::Unimplemented,
) = error.code
&& let ty::PredicateKind::Clause(ty::ClauseKind::Trait(
pred,
)) = error.obligation.predicate.kind().skip_binder()
{
self.infcx.err_ctxt().suggest_derive(
&error.obligation,
err,
error.obligation.predicate.kind().rebind(pred),
);
}
}
}
}
@@ -1552,6 +1604,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
})
}
}
if suggested_cloning { CloneSuggestion::Emitted } else { CloneSuggestion::NotEmitted }
}
/// Skip over locals that begin with an underscore or have no name

View File

@@ -14,7 +14,9 @@ use rustc_trait_selection::infer::InferCtxtExt;
use tracing::debug;
use crate::MirBorrowckCtxt;
use crate::diagnostics::{CapturedMessageOpt, DescribePlaceOpt, UseSpans};
use crate::diagnostics::{
BorrowedContentSource, CapturedMessageOpt, CloneSuggestion, DescribePlaceOpt, UseSpans,
};
use crate::prefixes::PrefixSet;
#[derive(Debug)]
@@ -269,14 +271,19 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
.span_delayed_bug(span, "Type may implement copy, but there is no other error.");
return;
}
let mut has_clone_suggestion = CloneSuggestion::NotEmitted;
let mut err = match kind {
&IllegalMoveOriginKind::BorrowedContent { target_place } => self
.report_cannot_move_from_borrowed_content(
&IllegalMoveOriginKind::BorrowedContent { target_place } => {
let (diag, clone_sugg) = self.report_cannot_move_from_borrowed_content(
original_path,
target_place,
span,
use_spans,
),
);
has_clone_suggestion = clone_sugg;
diag
}
&IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
self.cannot_move_out_of_interior_of_drop(span, ty)
}
@@ -285,7 +292,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
};
self.add_move_hints(error, &mut err, span);
self.add_move_hints(error, &mut err, span, has_clone_suggestion);
self.buffer_error(err);
}
@@ -426,7 +433,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
deref_target_place: Place<'tcx>,
span: Span,
use_spans: Option<UseSpans<'tcx>>,
) -> Diag<'infcx> {
) -> (Diag<'infcx>, CloneSuggestion) {
let tcx = self.infcx.tcx;
// Inspect the type of the content behind the
// borrow to provide feedback about why this
@@ -447,8 +454,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let decl = &self.body.local_decls[local];
let local_name = self.local_name(local).map(|sym| format!("`{sym}`"));
if decl.is_ref_for_guard() {
return self
.cannot_move_out_of(
return (
self.cannot_move_out_of(
span,
&format!(
"{} in pattern guard",
@@ -458,9 +465,14 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
.with_note(
"variables bound in patterns cannot be moved from \
until after the end of the pattern guard",
);
),
CloneSuggestion::NotEmitted,
);
} else if decl.is_ref_to_static() {
return self.report_cannot_move_from_static(move_place, span);
return (
self.report_cannot_move_from_static(move_place, span),
CloneSuggestion::NotEmitted,
);
}
}
@@ -539,10 +551,12 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
has_suggest_reborrow: false,
maybe_reinitialized_locations_is_empty: true,
};
if let Some(use_spans) = use_spans {
self.explain_captures(&mut err, span, span, use_spans, move_place, msg_opt);
}
err
let suggested_cloning = if let Some(use_spans) = use_spans {
self.explain_captures(&mut err, span, span, use_spans, move_place, msg_opt)
} else {
CloneSuggestion::NotEmitted
};
(err, suggested_cloning)
}
fn report_closure_move_error(
@@ -640,8 +654,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
// Check whether one of the where-bounds requires the closure to impl `Fn[Mut]`
// or `AsyncFn[Mut]`.
for (pred, span) in predicates.predicates.iter().zip(predicates.spans.iter()) {
let pred = pred.skip_norm_wip();
let dominated_by_fn_trait = self
.closure_clause_kind(*pred, def_id, asyncness)
.closure_clause_kind(pred, def_id, asyncness)
.is_some_and(|kind| matches!(kind, ty::ClosureKind::Fn | ty::ClosureKind::FnMut));
if dominated_by_fn_trait {
// Found `<TyOfCapturingClosure as FnMut>` or
@@ -675,10 +690,52 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
}
fn add_move_hints(&self, error: GroupedMoveError<'tcx>, err: &mut Diag<'_>, span: Span) {
/// Suggest cloning via UFCS when a move occurs through a custom `Deref` impl.
///
/// A simple `.clone()` on a type like `MyBox<Vec<i32>>` would clone the wrapper,
/// not the inner `Vec<i32>`. Instead, we suggest `<Vec<i32> as Clone>::clone(&val)`.
fn suggest_cloning_through_overloaded_deref(
&self,
err: &mut Diag<'_>,
ty: Ty<'tcx>,
span: Span,
) -> CloneSuggestion {
let tcx = self.infcx.tcx;
let Some(clone_trait) = tcx.lang_items().clone_trait() else {
return CloneSuggestion::NotEmitted;
};
let Some(errors) =
self.infcx.type_implements_trait_shallow(clone_trait, ty, self.infcx.param_env)
else {
return CloneSuggestion::NotEmitted;
};
if !errors.is_empty() {
return CloneSuggestion::NotEmitted;
}
let sugg = vec![
(span.shrink_to_lo(), format!("<{ty} as Clone>::clone(&")),
(span.shrink_to_hi(), ")".to_string()),
];
err.multipart_suggestion(
"you can `clone` the value and consume it, but this might not be \
your desired behavior",
sugg,
Applicability::MaybeIncorrect,
);
CloneSuggestion::Emitted
}
fn add_move_hints(
&self,
error: GroupedMoveError<'tcx>,
err: &mut Diag<'_>,
span: Span,
has_clone_suggestion: CloneSuggestion,
) {
match error {
GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => {
self.add_borrow_suggestions(err, span);
self.add_borrow_suggestions(err, span, !binds_to.is_empty());
if binds_to.is_empty() {
let place_ty = move_from.ty(self.body, self.infcx.tcx).ty;
let place_desc = match self.describe_place(move_from.as_ref()) {
@@ -718,14 +775,43 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
None => "value".to_string(),
};
if let Some(expr) = self.find_expr(use_span) {
self.suggest_cloning(
err,
original_path.as_ref(),
place_ty,
expr,
Some(use_spans),
);
if has_clone_suggestion == CloneSuggestion::NotEmitted {
// Check if the move is directly through a custom Deref impl
// (e.g. `*my_box` where MyBox implements Deref).
// A simple `.clone()` would clone the wrapper type rather than
// the inner value, so we need a UFCS suggestion instead.
//
// However, if there are further projections after the deref
// (e.g. `(*rc).field`), the value accessed is already the inner
// type and a simple `.clone()` works correctly.
let needs_ufcs = original_path.projection.last()
== Some(&ProjectionElem::Deref)
&& original_path.iter_projections().any(|(place, elem)| {
matches!(elem, ProjectionElem::Deref)
&& matches!(
self.borrowed_content_source(place),
BorrowedContentSource::OverloadedDeref(_)
| BorrowedContentSource::OverloadedIndex(_)
)
});
let emitted_ufcs = if needs_ufcs {
self.suggest_cloning_through_overloaded_deref(err, place_ty, use_span)
} else {
CloneSuggestion::NotEmitted
};
if emitted_ufcs == CloneSuggestion::NotEmitted {
if let Some(expr) = self.find_expr(use_span) {
self.suggest_cloning(
err,
original_path.as_ref(),
place_ty,
expr,
Some(use_spans),
);
}
}
}
if let Some(upvar_field) = self
@@ -787,29 +873,67 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
}
fn add_borrow_suggestions(&self, err: &mut Diag<'_>, span: Span) {
fn add_borrow_suggestions(
&self,
err: &mut Diag<'_>,
span: Span,
is_destructuring_pattern_move: bool,
) {
match self.infcx.tcx.sess.source_map().span_to_snippet(span) {
Ok(snippet) if snippet.starts_with('*') => {
let sp = span.with_lo(span.lo() + BytePos(1));
let inner = self.find_expr(sp);
let mut is_raw_ptr = false;
let mut is_ref = false;
let mut is_destructuring_assignment = false;
let mut is_nested_deref = false;
if let Some(inner) = inner {
is_nested_deref =
matches!(inner.kind, hir::ExprKind::Unary(hir::UnOp::Deref, _));
let typck_result = self.infcx.tcx.typeck(self.mir_def_id());
if let Some(inner_type) = typck_result.node_type_opt(inner.hir_id) {
if matches!(inner_type.kind(), ty::RawPtr(..)) {
is_raw_ptr = true;
} else if matches!(inner_type.kind(), ty::Ref(..)) {
is_ref = true;
}
}
is_destructuring_assignment =
self.infcx.tcx.hir_parent_iter(inner.hir_id).any(|(_, node)| {
matches!(
node,
hir::Node::LetStmt(&hir::LetStmt {
source: hir::LocalSource::AssignDesugar,
..
})
)
});
}
// If the `inner` is a raw pointer, do not suggest removing the "*", see #126863
// FIXME: need to check whether the assigned object can be a raw pointer, see `tests/ui/borrowck/issue-20801.rs`.
if !is_raw_ptr {
if is_raw_ptr {
return;
}
if !is_destructuring_pattern_move || is_ref {
err.span_suggestion_verbose(
span.with_hi(span.lo() + BytePos(1)),
"consider removing the dereference here",
String::new(),
Applicability::MaybeIncorrect,
);
} else if !is_destructuring_assignment && !is_nested_deref {
err.span_suggestion_verbose(
span.shrink_to_lo(),
"consider borrowing here",
'&',
Applicability::MaybeIncorrect,
);
} else {
err.span_help(
span,
"destructuring assignment cannot borrow from this expression; consider using a `let` binding instead",
);
}
}
_ => {

View File

@@ -493,7 +493,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
for (_, node) in self.infcx.tcx.hir_parent_iter(upvar_hir_id) {
if let Some(fn_decl) = node.fn_decl() {
if !matches!(
fn_decl.implicit_self,
fn_decl.implicit_self(),
hir::ImplicitSelfKind::RefImm | hir::ImplicitSelfKind::RefMut
) {
err.span_suggestion_verbose(
@@ -810,7 +810,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
&& let Some(ty) = sig.decl.inputs.get(local.index() - 1)
&& let hir::TyKind::Ref(_, mut_ty) = ty.kind
&& let hir::Mutability::Not = mut_ty.mutbl
&& sig.decl.implicit_self.has_implicit_self()
&& sig.decl.implicit_self().has_implicit_self()
{
Some(ty.span)
} else {
@@ -1147,7 +1147,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
arg_pos
.and_then(|pos| {
sig.decl.inputs.get(
pos + if sig.decl.implicit_self.has_implicit_self() {
pos + if sig.decl.implicit_self().has_implicit_self() {
1
} else {
0
@@ -1410,9 +1410,20 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
(span, " mut".to_owned(), true)
// If there is already a binding, we modify it to be `mut`.
} else if binding_exists {
// Shrink the span to just after the `&` in `&variable`.
let span = span.with_lo(span.lo() + BytePos(1)).shrink_to_lo();
(span, "mut ".to_owned(), true)
// Replace the sigil with the mutable version. We may be dealing
// with parser recovery here and cannot assume the user actually
// typed `&` or `*const`, so we compute the prefix from the snippet.
let Ok(src) = self.infcx.tcx.sess.source_map().span_to_snippet(span) else {
return;
};
let (prefix_len, replacement) = if local_decl.ty.is_ref() {
(src.chars().next().map_or(0, char::len_utf8), "&mut ")
} else {
(src.find("const").map_or(1, |i| i + "const".len()), "*mut ")
};
let ws_len = src[prefix_len..].len() - src[prefix_len..].trim_start().len();
let span = span.with_hi(span.lo() + BytePos((prefix_len + ws_len) as u32));
(span, replacement.to_owned(), true)
} else {
// Otherwise, suggest that the user annotates the binding; We provide the
// type of the local.

View File

@@ -9,6 +9,7 @@ use rustc_hir::def_id::DefId;
use rustc_middle::mir::{self, ConstraintCategory, Location};
use rustc_middle::ty::{
self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
Unnormalized,
};
use rustc_span::Span;
use rustc_trait_selection::error_reporting::infer::region::unexpected_hidden_region_diagnostic;
@@ -219,12 +220,12 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindOpaqueRegion<'_, 'tcx> {
fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
// If we find an opaque in a local ty, then for each of its captured regions,
// try to find a path between that captured regions and our borrow region...
if let ty::Alias(opaque @ ty::AliasTy { kind: ty::Opaque { def_id }, .. }) = *ty.kind()
if let ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = *ty.kind()
&& let hir::OpaqueTyOrigin::FnReturn { parent, in_trait_or_impl: None } =
self.tcx.opaque_ty_origin(def_id)
{
let variances = self.tcx.variances_of(def_id);
for (idx, (arg, variance)) in std::iter::zip(opaque.args, variances).enumerate() {
for (idx, (arg, variance)) in std::iter::zip(args, variances).enumerate() {
// Skip uncaptured args.
if *variance == ty::Bivariant {
continue;
@@ -276,12 +277,13 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for CheckExplicitRegionMentionAndCollectGen
fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
match *ty.kind() {
ty::Alias(opaque @ ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
if self.seen_opaques.insert(def_id) {
for (bound, _) in self
.tcx
.explicit_item_bounds(def_id)
.iter_instantiated_copied(self.tcx, opaque.args)
.iter_instantiated_copied(self.tcx, args)
.map(Unnormalized::skip_norm_wip)
{
bound.visit_with(self)?;
}

View File

@@ -15,7 +15,8 @@ use rustc_middle::bug;
use rustc_middle::hir::place::PlaceBase;
use rustc_middle::mir::{AnnotationSource, ConstraintCategory, ReturnConstraint};
use rustc_middle::ty::{
self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitor, fold_regions,
self, FnSigKind, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitor,
fold_regions,
};
use rustc_span::{Ident, Span, kw};
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
@@ -595,7 +596,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
if let ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, .. }) = *output_ty.kind() {
output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity()
output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity().skip_norm_wip()
};
debug!("report_fnmut_error: output_ty={:?}", output_ty);
@@ -686,6 +687,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
|| (*category == ConstraintCategory::Assignment
&& self.regioncx.universal_regions().defining_ty.is_fn_def())
|| self.regioncx.universal_regions().defining_ty.is_const()
|| (fr_name_and_span.is_none()
&& self.regioncx.universal_regions().defining_ty.is_fn_def())
{
return self.report_general_error(errci);
}
@@ -930,7 +933,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
debug!(?fn_did, ?args);
// Only suggest this on function calls, not closures
let ty = tcx.type_of(fn_did).instantiate_identity();
let ty = tcx.type_of(fn_did).instantiate_identity().skip_norm_wip();
debug!("ty: {:?}, ty.kind: {:?}", ty, ty.kind());
if let ty::Closure(_, _) = ty.kind() {
return;
@@ -1050,7 +1053,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
else {
return;
};
let ty::Closure(_, args) = *tcx.type_of(closure_def_id).instantiate_identity().kind()
let ty::Closure(_, args) =
*tcx.type_of(closure_def_id).instantiate_identity().skip_norm_wip().kind()
else {
return;
};
@@ -1081,14 +1085,14 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
// Build a new closure where the return type is an owned value, instead of a ref.
let fn_sig_kind =
FnSigKind::default().set_safe(true).set_c_variadic(liberated_sig.c_variadic());
let closure_sig_as_fn_ptr_ty = Ty::new_fn_ptr(
tcx,
ty::Binder::dummy(tcx.mk_fn_sig(
liberated_sig.inputs().iter().copied(),
peeled_ty,
liberated_sig.c_variadic,
hir::Safety::Safe,
rustc_abi::ExternAbi::Rust,
fn_sig_kind,
)),
);
let closure_ty = Ty::new_closure(
@@ -1148,7 +1152,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let ocx = ObligationCtxt::new(&self.infcx);
ocx.register_obligations(preds.iter().map(|(pred, span)| {
trace!(?pred);
Obligation::misc(tcx, span, self.mir_def_id(), self.infcx.param_env, pred)
Obligation::misc(
tcx,
span,
self.mir_def_id(),
self.infcx.param_env,
pred.skip_norm_wip(),
)
}));
if ocx.evaluate_obligations_error_on_ambiguity().is_empty() && count > 0 {

View File

@@ -6,7 +6,7 @@ use rustc_errors::{Diag, EmissionGuarantee};
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_middle::ty::print::RegionHighlightMode;
use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, RegionVid, Ty};
use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, RegionVid, Ty, Unnormalized};
use rustc_middle::{bug, span_bug};
use rustc_span::{DUMMY_SP, Span, Symbol, kw, sym};
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
@@ -418,7 +418,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
// Get the parent fn's signature with liberated late-bound regions,
// so we have `ReLateParam` instead of `ReBound`.
let parent_fn_sig = tcx.fn_sig(parent_def_id).instantiate_identity();
let parent_fn_sig = tcx.fn_sig(parent_def_id).instantiate_identity().skip_norm_wip();
let liberated_sig = tcx.liberate_late_bound_regions(parent_def_id, parent_fn_sig);
let parent_param_ty = *liberated_sig.inputs().get(param_index)?;
@@ -499,18 +499,18 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
fr: RegionVid,
) -> Option<RegionName> {
let implicit_inputs = self.regioncx.universal_regions().defining_ty.implicit_inputs();
let argument_index = self.regioncx.get_argument_index_for_region(self.infcx.tcx, fr)?;
let user_arg_index = self.regioncx.get_user_arg_index_for_region(self.infcx.tcx, fr)?;
let arg_ty = self.regioncx.universal_regions().unnormalized_input_tys
[implicit_inputs + argument_index];
[implicit_inputs + user_arg_index];
let (_, span) = self.regioncx.get_argument_name_and_span_for_region(
self.body,
self.local_names(),
argument_index,
user_arg_index,
);
let highlight = self
.get_argument_hir_ty_for_highlighting(argument_index)
.get_argument_hir_ty_for_highlighting(user_arg_index)
.and_then(|arg_hir_ty| self.highlight_if_we_can_match_hir_ty(fr, arg_ty, arg_hir_ty))
.unwrap_or_else(|| {
// `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
@@ -528,10 +528,11 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
fn get_argument_hir_ty_for_highlighting(
&self,
argument_index: usize,
user_arg_index: usize,
) -> Option<&hir::Ty<'tcx>> {
let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(self.mir_hir_id())?;
let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(argument_index)?;
// Closures don't have implicit self arguments in HIR, so use `user_arg_index` directly.
let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(user_arg_index)?;
match argument_hir_ty.kind {
// This indicates a variable with no type annotation, like
// `|x|`... in that case, we can't highlight the type but
@@ -1023,10 +1024,10 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
return None;
};
let found = tcx
.any_free_region_meets(&tcx.type_of(region_parent).instantiate_identity(), |r| {
r.kind() == ty::ReEarlyParam(region)
});
let found = tcx.any_free_region_meets(
&tcx.type_of(region_parent).instantiate_identity().skip_norm_wip(),
|r| r.kind() == ty::ReEarlyParam(region),
);
Some(RegionName {
name: self.synthesize_region_name(),
@@ -1051,12 +1052,15 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
return None;
};
let predicates = self
let predicates: Vec<_> = self
.infcx
.tcx
.predicates_of(self.body.source.def_id())
.instantiate_identity(self.infcx.tcx)
.predicates;
.predicates
.into_iter()
.map(Unnormalized::skip_norm_wip)
.collect();
if let Some(upvar_index) = self
.regioncx

View File

@@ -31,7 +31,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
})
.or_else(|| {
debug!("get_var_name_and_span_for_region: attempting argument");
self.get_argument_index_for_region(tcx, fr).and_then(|index| {
self.get_user_arg_index_for_region(tcx, fr).and_then(|index| {
let local = self.user_arg_index_to_local(body, index);
if body_uses_local(body, local) {
Some(self.get_argument_name_and_span_for_region(body, local_names, index))
@@ -93,26 +93,26 @@ impl<'tcx> RegionInferenceContext<'tcx> {
///
/// N.B., in the case of a closure, the index is indexing into the signature as seen by the
/// user - in particular, index 0 is not the implicit self parameter.
pub(crate) fn get_argument_index_for_region(
pub(crate) fn get_user_arg_index_for_region(
&self,
tcx: TyCtxt<'tcx>,
fr: RegionVid,
) -> Option<usize> {
let implicit_inputs = self.universal_regions().defining_ty.implicit_inputs();
let argument_index =
let user_arg_index =
self.universal_regions().unnormalized_input_tys.iter().skip(implicit_inputs).position(
|arg_ty| {
debug!("get_argument_index_for_region: arg_ty = {arg_ty:?}");
debug!("get_user_arg_index_for_region: arg_ty = {arg_ty:?}");
tcx.any_free_region_meets(arg_ty, |r| r.as_var() == fr)
},
)?;
debug!(
"get_argument_index_for_region: found {fr:?} in argument {argument_index} which has type {:?}",
self.universal_regions().unnormalized_input_tys[argument_index],
"get_user_arg_index_for_region: found {fr:?} in argument {user_arg_index} which has type {:?}",
self.universal_regions().unnormalized_input_tys[user_arg_index],
);
Some(argument_index)
Some(user_arg_index)
}
/// Given the index of an argument as seen from the user (i.e. excluding
@@ -128,9 +128,9 @@ impl<'tcx> RegionInferenceContext<'tcx> {
&self,
body: &Body<'tcx>,
local_names: &IndexSlice<Local, Option<Symbol>>,
argument_index: usize,
user_arg_index: usize,
) -> (Option<Symbol>, Span) {
let argument_local = self.user_arg_index_to_local(body, argument_index);
let argument_local = self.user_arg_index_to_local(body, user_arg_index);
debug!("get_argument_name_and_span_for_region: argument_local={argument_local:?}");
let argument_name = local_names[argument_local];

View File

@@ -107,7 +107,7 @@ impl LocalizedConstraintGraphVisitor for LocalizedOutlivesConstraintCollector {
/// - a mermaid graph of the NLL regions and the constraints between them
/// - a mermaid graph of the NLL SCCs and the constraints between them
fn emit_polonius_dump<'tcx>(
dumper: &MirDumper<'_, '_, 'tcx>,
dumper: &MirDumper<'_, 'tcx>,
body: &Body<'tcx>,
regioncx: &RegionInferenceContext<'tcx>,
borrow_set: &BorrowSet<'tcx>,
@@ -186,7 +186,7 @@ fn emit_polonius_dump<'tcx>(
/// Emits the polonius MIR, as escaped HTML.
fn emit_html_mir<'tcx>(
dumper: &MirDumper<'_, '_, 'tcx>,
dumper: &MirDumper<'_, 'tcx>,
body: &Body<'tcx>,
out: &mut dyn io::Write,
) -> io::Result<()> {

View File

@@ -2,7 +2,7 @@ use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def_id::DefId;
use rustc_middle::bug;
use rustc_middle::ty::{
self, GenericArgsRef, Region, RegionVid, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
self, Flags, GenericArgsRef, Region, RegionVid, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
TypeVisitor,
};
use tracing::{debug, instrument};
@@ -177,7 +177,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for CollectMemberConstraintsVisitor<'_, '_,
| ty::Coroutine(def_id, args) => self.visit_closure_args(def_id, args),
ty::Alias(ty::AliasTy { kind, args, .. })
if let Some(variances) = self.cx().opt_alias_variances(kind, kind.def_id()) =>
if let Some(variances) = self.cx().opt_alias_variances(kind) =>
{
// Skip lifetime parameters that are not captured, since they do
// not need member constraints registered for them; we'll erase

View File

@@ -10,9 +10,9 @@ use rustc_infer::traits::ObligationCause;
use rustc_macros::extension;
use rustc_middle::mir::{Body, ConstraintCategory};
use rustc_middle::ty::{
self, DefiningScopeKind, DefinitionSiteHiddenType, FallibleTypeFolder, GenericArg,
self, DefiningScopeKind, DefinitionSiteHiddenType, FallibleTypeFolder, Flags, GenericArg,
GenericArgsRef, OpaqueTypeKey, ProvisionalHiddenType, Region, RegionVid, Ty, TyCtxt,
TypeFoldable, TypeSuperFoldable, TypeVisitableExt, fold_regions,
TypeFoldable, TypeSuperFoldable, TypeVisitableExt, Unnormalized, fold_regions,
};
use rustc_mir_dataflow::points::DenseLocationMap;
use rustc_span::Span;
@@ -501,7 +501,7 @@ impl<'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for ToArgRegionsFolder<'_, 'tcx> {
}
ty::Alias(ty::AliasTy { kind, args, .. })
if let Some(variances) = tcx.opt_alias_variances(kind, kind.def_id()) =>
if let Some(variances) = tcx.opt_alias_variances(kind) =>
{
let args = tcx.mk_args_from_iter(std::iter::zip(variances, args.iter()).map(
|(&v, s)| {
@@ -569,16 +569,17 @@ pub(crate) fn apply_definition_site_hidden_types<'tcx>(
};
// We erase all non-member region of the opaque and need to treat these as existentials.
let expected_ty =
ty::fold_regions(tcx, expected.ty.instantiate(tcx, key.args), |re, _dbi| {
match re.kind() {
ty::ReErased => infcx.next_nll_region_var(
NllRegionVariableOrigin::Existential { name: None },
|| crate::RegionCtxt::Existential(None),
),
_ => re,
}
});
let expected_ty = ty::fold_regions(
tcx,
expected.ty.instantiate(tcx, key.args).skip_norm_wip(),
|re, _dbi| match re.kind() {
ty::ReErased => infcx.next_nll_region_var(
NllRegionVariableOrigin::Existential { name: None },
|| crate::RegionCtxt::Existential(None),
),
_ => re,
},
);
// We now simply equate the expected with the actual hidden type.
let locations = Locations::All(hidden_type.span);
@@ -598,8 +599,13 @@ pub(crate) fn apply_definition_site_hidden_types<'tcx>(
body.source.def_id().expect_local(),
);
// We need to normalize both types in the old solver before equatingt them.
let actual_ty = ocx.normalize(&cause, infcx.param_env, hidden_type.ty);
let expected_ty = ocx.normalize(&cause, infcx.param_env, expected_ty);
let actual_ty = ocx.normalize(
&cause,
infcx.param_env,
Unnormalized::new_wip(hidden_type.ty),
);
let expected_ty =
ocx.normalize(&cause, infcx.param_env, Unnormalized::new_wip(expected_ty));
ocx.eq(&cause, infcx.param_env, actual_ty, expected_ty).map_err(|_| NoSolution)
},
"equating opaque types",

View File

@@ -5,7 +5,7 @@ use rustc_infer::infer::canonical::Canonical;
use rustc_infer::infer::outlives::env::RegionBoundPairs;
use rustc_middle::bug;
use rustc_middle::mir::{Body, ConstraintCategory};
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, Upcast};
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, Unnormalized, Upcast};
use rustc_span::Span;
use rustc_span::def_id::DefId;
use rustc_trait_selection::solve::NoSolution;
@@ -189,7 +189,11 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
where
T: type_op::normalize::Normalizable<'tcx> + fmt::Display + Copy + 'tcx,
{
self.normalize_with_category(value, location, ConstraintCategory::Boring)
self.normalize_with_category(
Unnormalized::new_wip(value),
location,
ConstraintCategory::Boring,
)
}
pub(super) fn deeply_normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
@@ -207,13 +211,14 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
#[instrument(skip(self), level = "debug")]
pub(super) fn normalize_with_category<T>(
&mut self,
value: T,
value: Unnormalized<'tcx, T>,
location: impl NormalizeLocation,
category: ConstraintCategory<'tcx>,
) -> T
where
T: type_op::normalize::Normalizable<'tcx> + fmt::Display + Copy + 'tcx,
{
let value = value.skip_normalization();
let param_env = self.infcx.param_env;
let result: Result<_, ErrorGuaranteed> = self.fully_perform_op(
location.to_locations(),
@@ -246,11 +251,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
CustomTypeOp::new(
|ocx| {
let structurally_normalize = |ty| {
ocx.structurally_normalize_ty(
&cause,
param_env,
ty,
)
ocx.structurally_normalize_ty(&cause, param_env, Unnormalized::new_wip(ty))
.unwrap_or_else(|_| bug!("struct tail should have been computable, since we computed it in HIR"))
};
@@ -295,7 +296,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
body.source.def_id().expect_local(),
),
param_env,
ty,
Unnormalized::new_wip(ty),
)
.map_err(|_| NoSolution)
},
@@ -364,7 +365,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
// obligation for the unnormalized user_ty here. This is
// where the "incorrectly skips the WF checks we normally do"
// happens
let user_ty = ocx.normalize(&cause, param_env, user_ty);
let user_ty = ocx.normalize(&cause, param_env, Unnormalized::new_wip(user_ty));
ocx.eq(&cause, param_env, user_ty, mir_ty)?;
Ok(())
},

View File

@@ -70,12 +70,14 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> {
#[instrument(skip(self), level = "debug")]
pub(super) fn convert_all(&mut self, query_constraints: &QueryRegionConstraints<'tcx>) {
let QueryRegionConstraints { outlives, assumptions } = query_constraints;
let QueryRegionConstraints { constraints, assumptions } = query_constraints;
let assumptions =
elaborate::elaborate_outlives_assumptions(self.infcx.tcx, assumptions.iter().copied());
for &(predicate, constraint_category) in outlives {
self.convert(predicate, constraint_category, &assumptions);
for &(constraint, constraint_category) in constraints {
constraint.iter_outlives().for_each(|predicate| {
self.convert(predicate, constraint_category, &assumptions);
});
}
}
@@ -292,8 +294,12 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> {
) {
Ok(TypeOpOutput { output: ty, constraints, .. }) => {
// FIXME(higher_ranked_auto): What should we do with the assumptions here?
if let Some(QueryRegionConstraints { outlives, assumptions: _ }) = constraints {
next_outlives_predicates.extend(outlives.iter().copied());
if let Some(QueryRegionConstraints { constraints, assumptions: _ }) = constraints {
next_outlives_predicates.extend(constraints.iter().flat_map(
|(constraint, category)| {
constraint.iter_outlives().map(|outlives| (outlives, *category))
},
));
}
ty
}

View File

@@ -32,6 +32,15 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
return;
}
// If the MIR body was constructed via `construct_error` (because an
// earlier pass like match checking failed), its args may not match
// the user-provided signature (e.g. a coroutine with too many
// parameters). Bail out as this can cause panic,
// see <https://github.com/rust-lang/rust/issues/139570>.
if self.body.tainted_by_errors.is_some() {
return;
}
let user_provided_poly_sig = self.tcx().closure_user_provided_sig(mir_def_id);
// Instantiate the canonicalized variables from user-provided signature
@@ -94,9 +103,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
user_provided_sig = self.tcx().mk_fn_sig(
user_provided_sig.inputs().iter().copied(),
output_ty,
user_provided_sig.c_variadic,
user_provided_sig.safety,
user_provided_sig.abi,
user_provided_sig.fn_sig_kind,
);
}

View File

@@ -1015,7 +1015,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
if let ty::FnDef(def_id, _) = *src_ty.kind()
&& let ty::FnPtr(_, target_hdr) = *ty.kind()
&& tcx.codegen_fn_attrs(def_id).safe_target_features
&& target_hdr.safety.is_safe()
&& target_hdr.safety().is_safe()
&& let Some(safe_sig) = tcx.adjust_target_feature_sig(
def_id,
src_sig,
@@ -1759,7 +1759,8 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
);
}
} else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
let unnormalized_ty = tcx.type_of(static_def_id).instantiate_identity();
let unnormalized_ty =
tcx.type_of(static_def_id).instantiate_identity().skip_norm_wip();
let normalized_ty = self.normalize(unnormalized_ty, locations);
let literal_ty = constant.const_.ty().builtin_deref(true).unwrap();
@@ -1971,7 +1972,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
term_location: Location,
call_source: CallSource,
) {
if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic())
{
span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
}

Some files were not shown because too many files have changed in this diff Show More