Commit Graph

8320 Commits

Author SHA1 Message Date
bors 37d56daac6 Auto merge of #128771 - carbotaniuman:stabilize_unsafe_attr, r=nnethercote
Stabilize `unsafe_attributes`

# Stabilization report

## Summary

This is a tracking issue for the RFC 3325: unsafe attributes

We are stabilizing `#![feature(unsafe_attributes)]`,  which makes certain attributes considered 'unsafe', meaning that they must be surrounded by an `unsafe(...)`, as in `#[unsafe(no_mangle)]`.

RFC: rust-lang/rfcs#3325
Tracking issue: #123757

## What is stabilized

### Summary of stabilization

Certain attributes will now be designated as unsafe attributes, namely, `no_mangle`, `export_name`, and `link_section` (stable only), and these attributes will need to be called by surrounding them in `unsafe(...)` syntax. On editions prior to 2024, this is simply an edition lint, but it will become a hard error in 2024. This also works in `cfg_attr`, but `unsafe` is not allowed for any other attributes, including proc-macros ones.

```rust
#[unsafe(no_mangle)]
fn a() {}

#[cfg_attr(any(), unsafe(export_name = "c"))]
fn b() {}
```

For a table showing the attributes that were considered to be included in the list to require unsafe, and subsequent reasoning about why each such attribute was or was not included, see [this comment here](https://github.com/rust-lang/rust/pull/124214#issuecomment-2124753464)

## Tests

The relevant tests are in `tests/ui/rust-2024/unsafe-attributes` and `tests/ui/attributes/unsafe`.
2024-08-17 22:48:42 +00:00
bors feeba198f2 Auto merge of #128792 - compiler-errors:foreign-sig, r=spastorino
Use `FnSig` instead of raw `FnDecl` for `ForeignItemKind::Fn`, fix ICE for `Fn` trait error on safe foreign fn

Let's use `hir::FnSig` instead of `hir::FnDecl + hir::Safety` for `ForeignItemKind::Fn`. This consolidates some handling code between normal fns and foreign fns.

Separetly, fix an ICE where we weren't handling `Fn` trait errors for safe foreign fns.

If perf is bad for the first commit, I can rework the ICE fix to not rely on it. But if perf is good, I prefer we fix and clean up things all at once 👍

r? spastorino

Fixes #128764
2024-08-17 19:35:01 +00:00
Matthias Krüger ddbbda47eb
Rollup merge of #129168 - BoxyUwU:mismatched_ty_correct_id, r=compiler-errors
Return correct HirId when finding body owner in diagnostics

Fixes #129145
Fixes #128810

r? ```@compiler-errors```

```rust
fn generic<const N: u32>() {}

trait Collate<const A: u32> {
    type Pass;
    fn collate(self) -> Self::Pass;
}

impl<const B: u32> Collate<B> for i32 {
    type Pass = ();
    fn collate(self) -> Self::Pass {
        generic::<{ true }>()
        //~^ ERROR: mismatched types
    }
}
```

When type checking the `{ true }` anon const we would error with a type mismatch. This then results in diagnostics code attempting to check whether its due to a type mismatch with the return type. That logic was implemented by walking up the hir until we reached the body owner, except instead of using the `enclosing_body_owner` function it special cased various hir nodes incorrectly resulting in us walking out of the anon const and stopping at `fn collate` instead.

This then resulted in diagnostics logic inside of the anon consts `ParamEnv` attempting to do trait solving involving the `<i32 as Collate<B>>::Pass` type which ICEs because it is in the wrong environment.

I have rewritten this function to just walk up until it hits the `enclosing_body_owner` and made some other changes since I found this pretty hard to read/understand. Hopefully it's easier to understand now, it also makes it more obvious that this is not implemented in a very principled way and is definitely missing cases :)
2024-08-17 18:18:19 +02:00
Matthias Krüger cfeded47a4
Rollup merge of #128989 - s7tya:check-linkage-attribute-pos, r=petrochenkov
Emit an error for invalid use of the linkage attribute

fixes #128486

Currently, the use of the linkage attribute for Mod, Impl,... is incorrectly permitted. This PR will correct this issue by generating errors, and I've also added some UI test cases for it.

Related: #128552.
2024-08-17 18:18:18 +02:00
bors 426a60abc2 Auto merge of #128598 - RalfJung:float-comments, r=workingjubilee
float to/from bits and classify: update for float semantics RFC

With https://github.com/rust-lang/rfcs/pull/3514 having been accepted, it is clear that hardware which e.g. flushes subnormal to zero is just non-conformant from a Rust perspective -- this is a hardware bug, or maybe an LLVM backend bug (where LLVM doesn't lower floating-point ops in a way that they have the standardized behavior). So update the comments here to make it clear that we don't have to do any of this, we're just being nice.

Also remove the subnormal/NaN checks from the (unstable) const-version of to/from-bits; they are not needed since we decided with the aforementioned RFC that it is okay to get a different result at const-time and at run-time.

r? `@workingjubilee` since I think you wrote many of the comments I am editing here.
2024-08-17 09:13:13 +00:00
Ralf Jung 5f33085a7f more clear NAN names and fix broken_floats logic
Co-authored-by: Jubilee <46493976+workingjubilee@users.noreply.github.com>
2024-08-17 10:26:59 +02:00
Ralf Jung 53e1a2ee46 disable problematic float-conv tests in i586 targets
also fix typo in const-float-bits-conv
2024-08-17 10:26:53 +02:00
Shina 3c8dad152b Emit an error for invalid use of the linkage attribute 2024-08-17 15:03:20 +09:00
Boxy ed6315b3fe Rewrite `get_fn_id_for_return_block` 2024-08-16 20:53:13 +01:00
Michael Goulet 84633f47f6 Simplify cleaning foreign fns in rustdoc 2024-08-16 14:10:06 -04:00
Michael Goulet d850f85055 Don't ICE on Fn trait error for foreign fn 2024-08-16 14:10:06 -04:00
Michael Goulet 833af65f38 Use FnSig instead of raw FnDecl for ForeignItemKind::Fn 2024-08-16 14:10:06 -04:00
Matthias Krüger 5bceee4762
Rollup merge of #129154 - wafarm:fix-95463, r=estebank
Fix wrong source location for some incorrect macro definitions

Fixes #95463

Currently the code will consume the next token tree after `var` when trying to parse `$var:some_type` even when it's not a `:` (e.g. a `$` when input is `($foo $bar:tt) => {}`). Additionally it will return the wrong span when it's not a `:`.

This PR fixes these problems.
2024-08-16 19:58:59 +02:00
Matthias Krüger f04d25fa91
Rollup merge of #129042 - Jaic1:fix-116308, r=BoxyUwU
Special-case alias ty during the delayed bug emission in `try_from_lit`

This PR tries to fix #116308.

A delayed bug in `try_from_lit` will not be emitted so that the compiler will not ICE when it sees the pair `(ast::LitKind::Int, ty::TyKind::Alias)` in `lit_to_const` (called from `try_from_lit`).

This PR is related to an unstable feature `adt_const_params` (#95174).

r? ``@BoxyUwU``
2024-08-16 19:58:58 +02:00
Wafarm e03cc14b7a
Fix wrong source location for some incorrect macro definitions 2024-08-16 21:27:06 +08:00
Ralf Jung 368a4c6808 float to/from bits and classify: update comments regarding non-conformant hardware 2024-08-16 10:11:36 +02:00
Jaic1 cd2b0309cc Special-case alias ty in `try_from_lit` 2024-08-16 08:37:19 +08:00
Nicholas Nethercote 9d31f86f0d Overhaul token collection.
This commit does the following.

- Renames `collect_tokens_trailing_token` as `collect_tokens`, because
  (a) it's annoying long, and (b) the `_trailing_token` bit is less
  accurate now that its types have changed.

- In `collect_tokens`, adds a `Option<CollectPos>` argument and a
  `UsePreAttrPos` in the return type of `f`. These are used in
  `parse_expr_force_collect` (for vanilla expressions) and in
  `parse_stmt_without_recovery` (for two different cases of expression
  statements). Together these ensure are enough to fix all the problems
  with token collection and assoc expressions. The changes to the
  `stringify.rs` test demonstrate some of these.

- Adds a new test. The code in this test was causing an assertion
  failure prior to this commit, due to an invalid `NodeRange`.

The extra complexity is annoying, but necessary to fix the existing
problems.
2024-08-16 09:07:55 +10:00
Nicholas Nethercote fe460ac28b Add some attribute `stringify!` tests.
A couple of these are marked `FIXME` because they demonstrate existing
bugs with token collection.
2024-08-16 09:07:31 +10:00
Matthias Krüger 6c898d2b03
Rollup merge of #129101 - compiler-errors:deref-on-parent-by-ref, r=lcnr
Fix projections when parent capture is by-ref but child capture is by-value in the `ByMoveBody` pass

This fixes a somewhat strange bug where we build the incorrect MIR in #129074. This one is weird, but I don't expect it to actually matter in practice since it almost certainly results in a move error in borrowck. However, let's not ICE.

Given the code:

```
#![feature(async_closure)]

// NOT copy.
struct Ty;

fn hello(x: &Ty) {
    let c = async || {
        *x;
        //~^ ERROR cannot move out of `*x` which is behind a shared reference
    };
}

fn main() {}
```

The parent coroutine-closure captures `x: &Ty` by-ref, resulting in an upvar of `&&Ty`. The child coroutine captures `x` by-value, resulting in an upvar of `&Ty`. When constructing the by-move body for the coroutine-closure, we weren't applying an additional deref projection to convert the parent capture into the child capture, resulting in an type error in assignment, which is a validation ICE.

As I said above, this only occurs (AFAICT) in code that eventually results in an error, because it is only triggered by HIR that attempts to move a non-copy value out of a ref. This doesn't occur if `Ty` is `Copy`, since we'd instead capture `x` by-ref in the child coroutine.

Fixes #129074
2024-08-15 19:32:37 +02:00
Matthias Krüger 53bf554de8
Rollup merge of #129072 - compiler-errors:more-powerful-async-closure-inference, r=lcnr
Infer async closure args from `Fn` bound even if there is no corresponding `Future` bound on return

In #127482, I implemented the functionality to infer an async closure signature when passed into a function that has `Fn` + `Future` where clauses that look like:

```
fn whatever(callback: F)
where
  F: Fn(Arg) -> Fut,
  Fut: Future<Output = Out>,
```

However, #127781 demonstrates that this is still incomplete to address the cases users care about. So let's not bail when we fail to find a `Future` bound, and try our best to just use the args from the `Fn` bound if we find it. This is *fine* since most users of closures only really care about the *argument* types for inference guidance, since we require the receiver of a `.` method call to be known in order to probe methods.

When I experimented with programmatically rewriting `|| async {}` to `async || {}` in #127827, this also seems to have fixed ~5000 regressions (probably all coming from usages `TryFuture`/`TryStream` from futures-rs): the [before](https://github.com/rust-lang/rust/pull/127827#issuecomment-2254061733) and [after](https://github.com/rust-lang/rust/pull/127827#issuecomment-2255470176) crater runs.

Fixes #127781.
2024-08-15 19:32:36 +02:00
Matthias Krüger 3075644a3d
Rollup merge of #128348 - dingxiangfei2009:allow-shadow-call-stack-sanitizer, r=tmandry
Unconditionally allow shadow call-stack sanitizer for AArch64

It is possible to do so whenever `-Z fixed-x18` is applied.

cc ``@Darksonn`` for context

The reasoning is that, as soon as reservation on `x18` is forced through the flag `fixed-x18`, on AArch64 the option to instrument with [Shadow Call Stack sanitizer](https://clang.llvm.org/docs/ShadowCallStack.html) is then applicable regardless of the target configuration.

At the every least, we would like to relax the restriction on specifically `aarch64-unknonw-none`. For this option, we can include a documentation change saying that users of compiled objects need to ensure that they are linked to runtime with Shadow Call Stack instrumentation support.

Related: #121972
2024-08-15 19:32:35 +02:00
Matthias Krüger 9938349c71
Rollup merge of #128925 - dingxiangfei2009:smart-ptr-helper-attr, r=compiler-errors
derive(SmartPointer): register helper attributes

Fix #128888

This PR enables built-in macros to register helper attributes, if any, to support correct name resolution in the correct lexical scope under the macros.

Also, `#[pointee]` is moved into the scope under `derive(SmartPointer)`.

cc `@Darksonn` `@davidtwco`
2024-08-15 00:02:25 +02:00
Matthias Krüger 0bed4d1f1c
Rollup merge of #125970 - RalfJung:before_exec, r=m-ou-se
CommandExt::before_exec: deprecate safety in edition 2024

Similar to `set_var`, we had to find out after 1.0 was released that `before_exec` should have been unsafe. We partially rectified this by deprecating that function a long time ago, but since https://github.com/rust-lang/rust/pull/124636 we have the ability to also deprecate the safety of the old function and make it a *hard error* to call the old function outside `unsafe` in the next edition. So just in case anyone still uses the old function, let's ensure this can't be ignored when moving code to the new edition.

Cc `@rust-lang/libs-api`

Tracking:

- https://github.com/rust-lang/rust/issues/124866
2024-08-15 00:02:24 +02:00
Michael Goulet 4290943fb3 Infer async closure args from Fn bound even if there is no corresponding Future bound 2024-08-14 15:33:03 -04:00
Michael Goulet 1e1d839388 Fix projections when parent capture is by-ref 2024-08-14 13:24:07 -04:00
许杰友 Jieyou Xu (Joe) 2200910659
Rollup merge of #129059 - compiler-errors:subtyping-correct-type, r=lcnr
Record the correct target type when coercing fn items/closures to pointers

Self-explanatory. We were previously not recording the *target* type of a coercion as the output of an adjustment. This should remedy that.

We must also modify the function pointer casts in MIR typeck to use subtyping, since those broke since #118247.

r? lcnr
2024-08-14 21:43:08 +08:00
许杰友 Jieyou Xu (Joe) 049b3e549e
Rollup merge of #128954 - zachs18:fromresidual-no-default, r=scottmcm
Explicitly specify type parameter on FromResidual for Option and ControlFlow.

~~Remove type parameter default `R = <Self as Try>::Residual` from `FromResidual`~~ _Specify default type parameter on `FromResidual` impls in the stdlib_ to work around https://github.com/rust-lang/rust/issues/99940 / https://github.com/rust-lang/rust/issues/87350 ~~as mentioned in https://github.com/rust-lang/rust/issues/84277#issuecomment-1773259264~~.

This does not completely fix the issue, but works around it for `Option` and `ControlFlow` specifically (`Result` does not have the issue since it already did not use the default parameter of `FromResidual`).

~~(Does this need an ACP or similar?)~~ ~~This probably needs at least an FCP since it changes the API described in [the RFC](https://github.com/rust-lang/rfcs/pull/3058). Not sure if T-lang, T-libs-api, T-libs, or some combination (The tracking issue is tagged T-lang, T-libs-api).~~ This probably doesn't need T-lang input, since it is not changing the API of `FromResidual` from the RFC? Maybe needs T-libs-api FCP?
2024-08-14 21:43:08 +08:00
许杰友 Jieyou Xu (Joe) 196d256b20
Rollup merge of #128570 - folkertdev:stabilize-asm-const, r=Amanieu
Stabilize `asm_const`

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

reference PR: https://github.com/rust-lang/reference/pull/1556

this will probably require some CI wrangling (and a rebase), so let's get that over with even though the final required PR is not merged yet.

r? `@ghost`
2024-08-14 21:43:07 +08:00
Ralf Jung 5ae03863de CommandExt::before_exec: deprecate safety in edition 2024 2024-08-14 14:04:11 +02:00
bors fbce03b195 Auto merge of #129060 - matthiaskrgr:rollup-s72gpif, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #122884 (Optimize integer `pow` by removing the exit branch)
 - #127857 (Allow to customize `// TODO:` comment for deprecated safe autofix)
 - #129034 (Add `#[must_use]` attribute to `Coroutine` trait)
 - #129049 (compiletest: Don't panic on unknown JSON-like output lines)
 - #129050 (Emit a warning instead of an error if `--generate-link-to-definition` is used with other output formats than HTML)
 - #129056 (Fix one usage of target triple in bootstrap)
 - #129058 (Add mw back to review rotation)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-08-14 06:43:26 +00:00
Matthias Krüger e01d6141a4
Rollup merge of #129062 - Nadrieril:fix-129009, r=compiler-errors
Remove a no-longer-true assert

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

The assert was simply no longer true. I thought my test suite was thorough but I had not noticed these `let`-specific diagnostics codepaths.

r? `@compiler-errors`
2024-08-14 05:05:53 +02:00
Matthias Krüger 85180cd365
Rollup merge of #128759 - notriddle:notriddle/spec-to-string, r=workingjubilee,compiler-errors
alloc: add ToString specialization for `&&str`

Fixes #128690
2024-08-14 05:05:51 +02:00
Folkert 8419c0956e stabilize `asm_const` 2024-08-13 23:18:31 +02:00
Nadrieril 249a588cad Remove a no-longer-true `assert` 2024-08-13 23:00:42 +02:00
Michael Goulet 5df13af56f Use the right type when coercing fn items to pointers 2024-08-13 16:23:20 -04:00
Matthias Krüger d4f5a89f6e
Rollup merge of #129034 - henryksloan:coroutine-must-use, r=joboet
Add `#[must_use]` attribute to `Coroutine` trait

[Coroutines tracking issue](https://github.com/rust-lang/rust/issues/43122)

Like closures (`FnOnce`, `AsyncFn`, etc.), coroutines are lazy and do nothing unless called (resumed). Closure traits like `FnOnce` have `#[must_use = "closures are lazy and do nothing unless called"]` to catch likely bugs for users of APIs that produce them. This PR adds such a `#[must_use]` attribute to `trait Coroutine`.
2024-08-13 21:11:13 +02:00
Matthias Krüger f68a28d95c
Rollup merge of #127857 - tbu-:pr_deprecated_safe_todo, r=petrochenkov
Allow to customize `// TODO:` comment for deprecated safe autofix

Relevant for the deprecation of `CommandExt::before_exit` in #125970.

Tracking:
- #124866
2024-08-13 21:11:12 +02:00
Michael Howell c6fb0f344e diagnostics: use `DeepRejectCtxt` for check
This makes more things match, particularly applicable blankets.
2024-08-13 10:01:13 -07:00
Matthias Krüger 41aa9631ef
Rollup merge of #129026 - rcvalle:rust-cfi-move-cfi-ui-tests-to-cfi-directory, r=compiler-errors
CFI: Move CFI ui tests to cfi directory

Move the CFI ui tests to the cfi directory and removes the cfi prefix from tests file names similarly to how the cfi codegen tests are organized.
2024-08-13 12:12:25 +02:00
Tobias Bucher 811d7dd113 `#[deprecated_safe_2024]`: Also use the `// TODO:` hint in the compiler error
This doesn't work for translated compiler error messages.
2024-08-13 11:32:47 +02:00
Tobias Bucher 399ef23d2b Allow to customize `// TODO:` comment for deprecated safe autofix
Relevant for the deprecation of `CommandExt::before_exit` in #125970.
2024-08-13 11:32:24 +02:00
bors 591ecb88df Auto merge of #128742 - RalfJung:miri-vtable-uniqueness, r=saethlin
miri: make vtable addresses not globally unique

Miri currently gives vtables a unique global address. That's not actually matching reality though. So this PR enables Miri to generate different addresses for the same type-trait pair.

To avoid generating an unbounded number of `AllocId` (and consuming unbounded amounts of memory), we use the "salt" technique that we also already use for giving constants non-unique addresses: the cache is keyed on a "salt" value n top of the actually relevant key, and Miri picks a random salt (currently in the range `0..16`) each time it needs to choose an `AllocId` for one of these globals -- that means we'll get up to 16 different addresses for each vtable. The salt scheme is integrated into the global allocation deduplication logic in `tcx`, and also used for functions and string literals. (So this also fixes the problem that casting the same function to a fn ptr over and over will consume unbounded memory.)

r? `@saethlin`
Fixes https://github.com/rust-lang/miri/issues/3737
2024-08-13 04:32:34 +00:00
Henry Sloan 1e445f48d4 Add must_use attribute to Coroutine trait 2024-08-12 19:27:57 -07:00
Ramon de C Valle 66c93ac8ba CFI: Move CFI ui tests to cfi directory
Moves the CFI ui tests to the cfi directory and removes the cfi prefix
from tests file names similarly to how the cfi codegen tests are
organized.
2024-08-12 14:59:50 -07:00
Matthias Krüger 85eb465a10
Rollup merge of #128912 - compiler-errors:do-not-recommend-impl, r=lcnr
Store `do_not_recommend`-ness in impl header

Alternative to #128674

It's less flexible, but also less invasive. Hopefully it's also performant. I'd recommend we think separately about the design for how to gate arbitrary diagnostic attributes moving forward.
2024-08-12 23:10:51 +02:00
Matthias Krüger 4c49418472
Rollup merge of #128712 - compiler-errors:normalize-borrowck, r=lcnr
Normalize struct tail properly for `dyn` ptr-to-ptr casting in new solver

Realized that the new solver didn't handle ptr-to-ptr casting correctly.

r? lcnr

Built on #128694
2024-08-12 23:10:50 +02:00
Ding Xiang Fei 5534cb0a4a
derive(SmartPointer): register helper attributes 2024-08-13 04:26:48 +08:00
Zachary S 1b6df71192 Explicitly specify type parameter on FromResidual impls in stdlib.
To work around coherence issue. Also adds regression test.
2024-08-12 12:54:18 -05:00
Guillaume Gomez 99a785d62d
Rollup merge of #128994 - nnethercote:fix-Parser-look_ahead-more, r=compiler-errors
Fix bug in `Parser::look_ahead`.

The special case was failing to handle invisible delimiters on one path.

Fixes (but doesn't close until beta backported) #128895.

r? `@davidtwco`
2024-08-12 17:09:20 +02:00