2129 Commits

Author SHA1 Message Date
Jacob Pratt
566c13c88e
Rollup merge of #145726 - aapoalas:reborrow-lang-experiment, r=petrochenkov
Experiment: Reborrow trait

Tracking issue: rust-lang/rust#145612

Starting off really small here: just introduce the unstable feature and the feature gate, and one of the two traits that the Reborrow experiment deals with.

### Cliff-notes explanation

The `Reborrow` trait is conceptually a close cousin of `Copy` with the exception that it disables the source (`self`) for the lifetime of the target / result of the reborrow action. It can be viewed as a method of `fn reborrow(self: Self<'a>) -> Self<'a>` with the compiler adding tracking of the resulting `Self<'a>` (or any value derived from it that retains the `'a` lifetime) to keep the `self` disabled for reads and writes.

No method is planned to be surfaced to the user, however, as reborrowing cannot be seen in code (except for method calls [`a.foo()` reborrows `a`] and explicit reborrows [`&*a`]) and thus triggering user-code in it could be viewed as "spooky action at a distance". Furthermore, the added compiler tracking cannot be seen on the method itself, violating the Golden Rule. Note that the userland "reborrow" method is not True Reborrowing, but rather a form of a "Fancy Deref":
```rust
fn reborrow(&'short self: Self<'long>) -> Self<'short>;
```
The lifetime shortening is the issue here: a reborrowed `Self` or any value derived from it is bound to the method that called `reborrow`, since `&'short` is effectively a local variable. True Reborrowing does not shorten the lifetime of the result.

To avoid having to introduce new kinds of references, new kinds of lifetime annotations, or a blessed trait method, no method will be introduced at all. Instead, the `Reborrow` trait is intended to be a derived trait that effectively reborrows each field individually; `Copy` fields end up just copying, while fields that themselves `Reborrow` get disabled in the source, usually leading to the source itself being disabled (some differences may appear with structs that contain multiple reborrowable fields). The goal of the experiment is to determine how the actual implementation here will shape out, and what the "bottom case" for the recursive / deriving `Reborrow` is.

`Reborrow` has a friend trait, `CoerceShared`, which is equivalent to a `&'a mut T -> &'a T` conversion. This is needed as a different trait and different operation due to the different semantics it enforces on the source: a `CoerceShared` operation only disables the source for writes / exclusive access for the lifetime of the result. That trait is not yet introduced in this PR, though there is no particular reason why it could not be introduced.
2025-08-22 22:00:55 -04:00
Jacob Pratt
45d5109ad8
Rollup merge of #145573 - veluca93:unsafe-force-target-feature, r=davidtwco
Add an experimental unsafe(force_target_feature) attribute.

This uses the feature gate for https://github.com/rust-lang/rust/issues/143352, but is described in https://github.com/rust-lang/rfcs/pull/3820 which is strongly tied to the experiment.
2025-08-22 22:00:51 -04:00
Jacob Pratt
2dbd411d22
Rollup merge of #144897 - fee1-dead-contrib:raw_lifetimes_printing, r=fmease
print raw lifetime idents with r#

This replaces rust-lang/rust#143185 and fixes rust-lang/rust#143150

cc ``@fmease``
2025-08-22 22:00:47 -04:00
bors
6545b05638 Auto merge of #145494 - cjgillot:span-decode-once, r=lqd
Only unpack span data once to compute end_point and next_point.

Split from https://github.com/rust-lang/rust/pull/144930
2025-08-22 21:43:06 +00:00
Deadbeef
4970127c33 address review comments 2025-08-22 13:16:44 +08:00
Deadbeef
1e5b5ba1e7 print raw lifetime idents with r# 2025-08-22 12:58:37 +08:00
Luca Versari
291da71b2a Add an experimental unsafe(force_target_feature) attribute.
This uses the feature gate for
https://github.com/rust-lang/rust/issues/143352, but is described in
https://github.com/rust-lang/rfcs/pull/3820 which is strongly tied to
the experiment.
2025-08-22 01:26:26 +02:00
Aapo Alasuutari
5af359162e Introduce Reborrow lang item and trait 2025-08-21 23:53:25 +03:00
bors
040a98af70 Auto merge of #144086 - clubby789:alloc-zeroed, r=nikic
Pass `alloc-variant-zeroed` to LLVM

Makes use of https://github.com/llvm/llvm-project/pull/138299 (once we pull in a version of LLVM with this attribute). ~~Unfortunately also requires https://github.com/llvm/llvm-project/pull/149336 to work.~~

Closes rust-lang/rust#104847
2025-08-20 17:16:34 +00:00
clubby789
8ea3b09381 Pass alloc-variant-zeroed to LLVM 2025-08-20 17:08:46 +01:00
许杰友 Jieyou Xu (Joe)
3134f22d8b
Rollup merge of #145505 - cjgillot:tweak-span-cache, r=petrochenkov
Simplify span caches

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

r? `@petrochenkov`
2025-08-19 19:45:37 +08:00
Stuart Cook
633cc0cc6c
Rollup merge of #142681 - 1c3t3a:sanitize-off-on, r=rcvalle
Remove the `#[no_sanitize]` attribute in favor of `#[sanitize(xyz = "on|off")]`

This came up during the sanitizer stabilization (rust-lang/rust#123617). Instead of a `#[no_sanitize(xyz)]` attribute, we would like to have a `#[sanitize(xyz = "on|off")]` attribute, which is more powerful and allows to be extended in the future (instead
of just focusing on turning sanitizers off). The implementation is done according to what was [discussed on Zulip](https://rust-lang.zulipchat.com/#narrow/channel/343119-project-exploit-mitigations/topic/Stabilize.20the.20.60no_sanitize.60.20attribute/with/495377292)).

The new attribute also works on modules, traits and impl items and thus enables usage as the following:
```rust
#[sanitize(address = "off")]
mod foo {
    fn unsanitized(..) {}

    #[sanitize(address = "on")]
    fn sanitized(..) {}
}

trait MyTrait {
  #[sanitize(address = "off")]
  fn unsanitized_default(..) {}
}

#[sanitize(thread = "off")]
impl MyTrait for () {
    ...
}
```

r? ```@rcvalle```
2025-08-19 14:18:16 +10:00
Bastian Kersting
95bdb34494 Remove the no_sanitize attribute in favor of sanitize
This removes the #[no_sanitize] attribute, which was behind an unstable
feature named no_sanitize. Instead, we introduce the sanitize attribute
which is more powerful and allows to be extended in the future (instead
of just focusing on turning sanitizers off).

This also makes sanitize(kernel_address = ..) attribute work with
-Zsanitize=address

To do it the same as how clang disables address sanitizer, we now
disable ASAN on sanitize(kernel_address = "off") and KASAN on
sanitize(address = "off").

The same was added to clang in https://reviews.llvm.org/D44981.
2025-08-18 08:45:28 +00:00
Stuart Cook
152b43c7cb
Rollup merge of #145208 - joshtriplett:mbe-derive, r=petrochenkov
Implement declarative (`macro_rules!`) derive macros (RFC 3698)

This is a draft for review, and should not be merged yet.

This is layered atop https://github.com/rust-lang/rust/pull/145153 , and has
only two additional commits atop that. The first handles parsing and provides a
test for various parse errors. The second implements expansion and handles
application.

This implements RFC 3698, "Declarative (`macro_rules!`) derive macros".
Tracking issue: https://github.com/rust-lang/rust/issues/143549

This has one remaining issue, which I could use some help debugging: in
`tests/ui/macros/macro-rules-derive-error.rs`, the diagnostics for
`derive(fn_only)` (for a `fn_only` with no `derive` rules) and
`derive(ForwardReferencedDerive)` both get emitted twice, as a duplicate
diagnostic.

From what I can tell via adding some debugging code,
`unresolved_macro_suggestions` is getting called twice from
`finalize_macro_resolutions` for each of them, because
`self.single_segment_macro_resolutions` has two entries for the macro, with two
different `parent_scope` values. I'm not clear on why that happened; it doesn't
happen with the equivalent code using attrs.

I'd welcome any suggestions for fixing this.
2025-08-18 15:31:10 +10:00
Stuart Cook
d92e1fe8d7
Rollup merge of #145206 - scrabsha:push-uxovoqzrxnlx, r=jdonszelmann
Port `#[custom_mir(..)]` to the new attribute system

r? ``````````@jdonszelmann``````````
2025-08-18 15:31:10 +10:00
Camille Gillot
1460cfe8ea Only unpack span data once. 2025-08-16 18:09:26 +00:00
Camille Gillot
a84373085e Simplify span_data_to_lines_and_cols. 2025-08-16 16:23:21 +00:00
bors
2e2642e641 Auto merge of #145304 - m-ou-se:simplify-panic, r=oli-obk
Revert "Partially outline code inside the panic! macro".

This reverts https://github.com/rust-lang/rust/pull/115670

Without any tests/benchmarks that show some improvement, it's hard to know whether the change had any positive effect. (And if it did, whether that effect is still achieved today.)
2025-08-16 10:15:46 +00:00
Jacob Pratt
2b1a288dfc
Rollup merge of #144922 - Kobzol:derive-from, r=nnethercote
Implement `#[derive(From)]`

Implements the `#[derive(From)]` feature ([tracking issue](https://github.com/rust-lang/rust/issues/144889), [RFC](https://github.com/rust-lang/rfcs/pull/3809)).

It allows deriving the `From` impl on structs and tuple structs with exactly one field. Some implementation notes:
- I wasn't exactly sure which spans to use in the derive generating code, so I just used `span` everywhere. I don't know if it's the Right Thing To Do. In particular the errors when `#[derive(From)]` is used on a struct with an unsized field are weirdly duplicated.
- I had to solve an import stability problem, where if I just added the unstable `macro From` to `core::convert`, previously working code like `use std::convert::From` would suddenly require an unstable feature gate, because rustc would think that you're trying to import the unstable macro. `@petrochenkov` suggested that I add the macro the the core prelude instead. This has worked well, although it only works in edition 2021+. Not sure if I botched the prelude somehow and it should live elsewhere (?).
- I had to add `Ty::AstTy`, because the `from` function receives an argument with the type of the single field, and the existing variants of the `Ty` enum couldn't represent an arbitrary type.
2025-08-15 18:13:28 -04:00
Jakub Beránek
1f3a7471bf
Implement #[derive(From)] 2025-08-15 12:07:15 +02:00
Jakub Beránek
f39085bb37
Add derive_from unstable feature 2025-08-15 12:06:20 +02:00
Sasha Pourcelot
51bccdd1ab Port #[custom_mir(..)] to the new attribute system 2025-08-15 11:19:29 +02:00
Josh Triplett
8fb98ef368 mbe: Parse macro derive rules
This handles various kinds of errors, but does not allow applying the
derive yet.

This adds the feature gate `macro_derive`.
2025-08-14 13:53:57 -07:00
Marcelo Domínguez
5c631041aa Basic implementation of autodiff intrinsic 2025-08-14 16:29:58 +00:00
Sasha Pourcelot
d435197afc Port the #[linkage] attribute to the new attribute system 2025-08-13 21:01:37 +02:00
Mara Bos
08acba3071 Revert "Partially outline code inside the panic! macro".
Without any tests/benchmarks that show some improvement, it's hard to
know whether the change had any positive effect at all. (And if it did,
whether that effect is still achieved today.)
2025-08-12 12:52:39 +02:00
Camille GILLOT
6dcc8617d3 Fix doc-comment. 2025-08-10 23:01:45 +00:00
Stuart Cook
484141038a
Rollup merge of #145132 - camsteffen:refactor-map-unit-fn, r=fee1-dead
Refactor map_unit_fn lint

Just some light refactoring.
2025-08-09 13:58:55 +10:00
Cameron Steffen
7670cdeb70 Refactor map_unit_fn lint 2025-08-08 15:01:01 -05:00
Josh Triplett
bad0d45b2d mbe: Parse macro attribute rules
This handles various kinds of errors, but does not allow applying the
attributes yet.

This adds the feature gate `macro_attr`.
2025-08-08 11:00:54 -07:00
Stuart Cook
c97e64a01d
Rollup merge of #144439 - xizheyin:symbol-rs, r=petrochenkov
Introduce ModernIdent type to unify macro 2.0 hygiene handling

This pr introduce ModernIdent type to unify macro 2.0 hygiene handling

1. Added ModernIdent type. Wraps Ident and automatically calls `normalize_to_macros_2_0()`
2. Unified identifier normalization. Replaced scattered ident.normalize_to_macros_2_0() calls with ModernIdent::new(ident)

r? ````@petrochenkov````
2025-08-07 20:49:44 +10:00
Stuart Cook
1cd368a744
Rollup merge of #138689 - jedbrown:jed/nvptx-target-feature, r=ZuseZ4
add nvptx_target_feature

Tracking issue: #141468 (nvptx), which is part of #44839 (catch-all arches)
The feature gate is `#![feature(nvptx_target_feature)]`

This exposes the target features `sm_20` through `sm_120a` [as defined](https://github.com/llvm/llvm-project/blob/llvmorg-20.1.1/llvm/lib/Target/NVPTX/NVPTX.td#L59-L85) by LLVM.

Cc: ``````@gonzalobg``````
``````@rustbot`````` label +O-NVPTX +A-target-feature
2025-08-07 20:49:36 +10:00
xizheyin
6e7b9d5149
Introduce ModernIdent type to unify macro 2.0 hygiene handling
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-08-06 21:19:09 +08:00
Samuel Tardieu
d082ff4c04
Rollup merge of #144478 - joshtriplett:doc-code-formatting-prep, r=Amanieu
Improve formatting of doc code blocks

We don't currently apply automatic formatting to doc comment code blocks. As a
result, it has built up various idiosyncracies, which make such automatic
formatting difficult. Some of those idiosyncracies also make things harder for
human readers or other tools.

This PR makes a few improvements to doc code formatting, in the hopes of making
future automatic formatting easier, as well as in many cases providing net
readability improvements.

I would suggest reading each commit separately, as each commit contains one
class of changes.
2025-08-02 11:24:24 +02:00
xizheyin
81176b1a6c
Create two methods to fix find_oldest_ancestor_in_same_ctxt
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-07-29 14:54:47 +08:00
bors
d242a8bd5a Auto merge of #144469 - Kivooeo:chains-cleanup, r=SparrowLii
Some `let chains` clean-up

Not sure if this kind of clean-up is welcoming because of size, but I decided to try out one

r? compiler
2025-07-28 05:25:23 +00:00
Kivooeo
b8eb046e6e use let chains in mir, resolve, target 2025-07-28 06:10:36 +05:00
Matthias Krüger
e0a42996d5
Rollup merge of #144385 - xizheyin:macro-hygiene, r=petrochenkov
Optimize performance by inline in macro hygiene system

I inline some small method in `rustc_span/src/hygiene.rs` and so on.
2025-07-27 10:19:01 +02:00
Josh Triplett
715088094c Improve and regularize comment placement in doc code
Because doc code does not get automatically formatted, some doc code has
creative placements of comments that automatic formatting can't handle.
Reformat those comments to make the resulting code support standard Rust
formatting without breaking; this is generally an improvement to
readability as well.

Some comments are not indented to the prevailing indent, and are instead
aligned under some bit of code. Indent them to the prevailing indent,
and put spaces *inside* the comments to align them with code.

Some comments span several lines of code (which aren't the line the
comment is about) and expect alignment. Reformat them into one comment
not broken up by unrelated intervening code.

Some comments are placed on the same line as an opening brace, placing
them effectively inside the subsequent block, such that formatting would
typically format them like a line of that block. Move those comments to
attach them to what they apply to.

Some comments are placed on the same line as a one-line braced block,
effectively attaching them to the closing brace, even though they're
about the code inside the block. Reformat to make sure the comment will
stay on the same line as the code it's commenting.
2025-07-25 22:02:09 -07:00
xizheyin
60d69804ba
Inline some methods in rustc_span hygiene
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-07-24 23:46:39 +08:00
许杰友 Jieyou Xu (Joe)
551cef9fc9
Rollup merge of #144212 - bjorn3:remove_unique_lang_item, r=oli-obk
Remove the ptr_unique lang item

Miri no longer uses it since https://github.com/rust-lang/miri/pull/4307.
2025-07-22 00:54:30 +08:00
bjorn3
fdf8bdb7a2 Remove the ptr_unique lang item
Miri no longer uses it.
2025-07-20 09:50:58 +00:00
Jieyou Xu
69b71e4410
Mitigate #[align] name resolution ambiguity regression with a rename
From `#[align]` -> `#[rustc_align]`. Attributes starting with `rustc`
are always perma-unstable and feature-gated by `feature(rustc_attrs)`.

See regression RUST-143834.

For the underlying problem where even introducing new feature-gated
unstable built-in attributes can break user code such as

```rs
macro_rules! align {
    () => {
        /* .. */
    };
}

pub(crate) use align; // `use` here becomes ambiguous
```

refer to RUST-134963.

Since the `#[align]` attribute is still feature-gated by
`feature(fn_align)`, we can rename it as a mitigation. Note that
`#[rustc_align]` will obviously mean that current unstable user code
using `feature(fn_aling)` will need additionally `feature(rustc_attrs)`,
but this is a short-term mitigation to buy time, and is expected to be
changed to a better name with less collision potential.

See
<https://rust-lang.zulipchat.com/#narrow/channel/238009-t-compiler.2Fmeetings/topic/.5Bweekly.5D.202025-07-17/near/529290371>
where mitigation options were considered.
2025-07-19 01:42:30 +08:00
Matthias Krüger
82fbbddf63
Rollup merge of #143925 - oli-obk:slice-const-partialeq, r=fee1-dead
Make slice comparisons const

This needed a fix for `derive_const`, too, as it wasn't usable in libcore anymore as trait impls need const stability attributes. I think we can't use the same system as normal trait impls while `const_trait_impl` is still unstable.

r? ```@fee1-dead```

cc rust-lang/rust#143800
2025-07-18 14:49:19 +02:00
Oli Scherer
250648e871 Make derive_const usable within libcore again
Also make it *only* usable on nightly
2025-07-17 15:42:54 +00:00
bors
8c12d76304 Auto merge of #142903 - cjgillot:local-def-path-hash, r=compiler-errors
Only inherit local hash for paths

`DefPathHash`, as the counterpart of `DefId` that is stable across compiler invocations, is comprised of 2 parts. The first one is the `StableCrateId`, stable form of `CrateNum`. The second is 64 complementary bits to identify the crate-local definition.

The current implementation always hashes the full 128 bits when (1) trying to create a new child `DefPathHash` or (2) hashing a `CrateNum` or a `LocalDefId`. But we only need half that information: `LocalDefId` means that the `StableCrateId` is always the current crate's ; `CrateNum` means that we do not care about the local part.

As stable hashing is very hot in the query system, in particular hashing definitions, this is a big deal.

We still want the local part to change when the `StableCrateId` changes, to make incr-compilation errors less painful, ie. increase the likelihood that if will magically disappear by changing some code.

This PR sprinkles some `#[inline]` attributes on small functions that appeared in profiles.
2025-07-17 08:36:42 +00:00
bors
f8f6997469 Auto merge of #144044 - fmease:rollup-kg413pt, r=fmease
Rollup of 15 pull requests

Successful merges:

 - rust-lang/rust#142304 (tests: Add `RUST_BACKTRACE` and `-Cpanic` revisions to `panic-main.rs` test)
 - rust-lang/rust#143388 (Various refactors to the LTO handling code)
 - rust-lang/rust#143409 (Enable xgot feature for mips64 musl targets)
 - rust-lang/rust#143592 (UWP: link ntdll functions using raw-dylib)
 - rust-lang/rust#143595 (add `const_make_global`; err for `const_allocate` ptrs if didn't call)
 - rust-lang/rust#143678 (Added error for invalid char cast)
 - rust-lang/rust#143820 (Fixed a core crate compilation failure when enabling the `optimize_for_size` feature on some targets)
 - rust-lang/rust#143829 (Trim `BorrowedCursor` API)
 - rust-lang/rust#143851 (ci cleanup: rustdoc-gui-test now installs browser-ui-test)
 - rust-lang/rust#143856 (Linting public reexport of private dependencies)
 - rust-lang/rust#143895 (Dont collect assoc ty item bounds from trait where clause for host effect predicates)
 - rust-lang/rust#143922 (Improve path segment joining)
 - rust-lang/rust#143964 (Fix handling of SCRIPT_ARG in docker images)
 - rust-lang/rust#144002 (Update poison.rs)
 - rust-lang/rust#144016 (trait_sel: `MetaSized` always holds temporarily)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-07-17 05:24:30 +00:00
Deadbeef
3f2dc2bd1a add const_make_global; err for const_allocate ptrs if didn't call
Co-Authored-By: Ralf Jung <post@ralfj.de>
Co-Authored-By: Oli Scherer <github333195615777966@oli-obk.de>
2025-07-16 00:32:12 +08:00
tiif
7356ff7517 Implement other logics 2025-07-15 13:48:30 +00:00
bors
e9182f195b Auto merge of #143461 - folkertdev:cfg-select-builtin-macro, r=petrochenkov
make `cfg_select` a builtin macro

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

This parses mostly the same as the `macro cfg_select` version, except:

1. wrapping in double brackets is no longer supported (or needed): `cfg_select {{ /* ... */ }}` is now rejected.
2. in an expression context, the rhs is no longer wrapped in a block, so that this now works:
  ```rust
  fn main() {
      println!(cfg_select! {
          unix => { "foo" }
          _ => { "bar" }
      });
  }
  ```
3. a single wildcard rule is now supported: `cfg_select { _ => 1 }` now works

I've also added an error if none of the rules evaluate to true, and warnings for any arms that follow the `_` wildcard rule.

cc `@traviscross` if I'm missing any feature that should/should not be included
r? `@petrochenkov` for the macro logic details
2025-07-13 18:34:13 +00:00