Commit Graph

9508 Commits

Author SHA1 Message Date
Ralf Jung
a741b33c14 when an intrinsic has a const-stable fallback body, we can easily expose it on stable 2024-11-04 23:27:46 +01:00
Ralf Jung
5069434c81 most const intrinsics don't need an explicit rustc_const_unstable any more 2024-11-04 23:27:46 +01:00
Ralf Jung
1f0ed2b0f5 add new rustc_const_stable_intrinsic attribute for const-stable intrinsics 2024-11-04 23:27:46 +01:00
Ralf Jung
10723c2896 remove support for extern-block const intrinsics 2024-11-04 23:27:45 +01:00
Ralf Jung
ffad9aac27 mark some target features as 'forbidden' so they cannot be (un)set
For now, this is just a warning, but should become a hard error in the future
2024-11-04 22:56:47 +01:00
Urgau
0bc622d251 Prefer pub(super) in unreachable_pub lint suggestion 2024-11-04 19:09:40 +01:00
Matthias Krüger
a4f323ce9c
Rollup merge of #132583 - mejrs:tuples, r=compiler-errors
Suggest creating unary tuples when types don't match a trait

When you want to have a variadic function, a common workaround to implement this is to create a trait and then implement that trait for various tuples. For example in `pyo3` there exists
```rust
/// Calls the object with only positional arguments.
pub fn call1(&self, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyAny> {
   ...
}
```

with various impls like
```rust
impl<A: IntoPy<PyObject> IntoPy<Py<PyAny>> for (A,)
impl<A: IntoPy<PyObject, B: IntoPy<PyObject> IntoPy<Py<PyAny>> for (A, B)
... etc
```

This means that if you want to call the method with a single item you have to create a unary tuple, like `(x,)`, rather than just `x`.

This PR implements a suggestion to do that, if applicable.
2024-11-04 18:12:48 +01:00
Matthias Krüger
909574e411
Rollup merge of #132559 - bvanjoi:fix-132534, r=compiler-errors
find the generic container rather than simply looking up for the assoc with const arg

Fixes #132534

This issue is caused by mismatched generic parameters. Previously, it tried to find `T` in `trait X`, but after this change, it will find `T` in `fn a`.

r? `@compiler-errors`  as this assertion was introduced by you.
2024-11-04 18:12:47 +01:00
Matthias Krüger
b9db639ea5
Rollup merge of #132544 - dianne:unstable-library-feature-backticks, r=compiler-errors
Use backticks instead of single quotes for library feature names in diagnostics

This PR changes the text of library feature errors for using unstable or body-unstable items. Displaying library feature names in backticks is consistent with other diagnostics (e.g. those from `rustc_passes`) and with the `reason`s on unstable attributes in the library. Additionally, this simplifies diagnostics when supporting multiple unstable attributes on items (see #131824) since `DiagSymbolList` also displays symbols using backticks.
2024-11-04 18:12:46 +01:00
mejrs
5a48fe2c20 Suggest creating unary tuples 2024-11-04 12:06:19 +01:00
Michael Goulet
e3bd6b27f3 Fix minicore, add tests based off of it 2024-11-04 04:51:32 +00:00
Michael Goulet
883f8705d4 Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
bohan
6026a0f6c9 find the generic container rather than simply looking up for the assoc with const arg 2024-11-04 12:17:44 +08:00
Jubilee
6bc7be5efa
Rollup merge of #132516 - taiki-e:asm-ui, r=workingjubilee
Add bad-reg inline assembly ui test for RISC-V and s390x

https://github.com/rust-lang/rust/pull/131341#discussion_r1826555431

> Btw, such unsupported registers are present in most architectures, but only aarch64/arm64ec, x86_64, and not yet merged [sparc/sparc64](https://github.com/rust-lang/rust/pull/132472/files#diff-02aebda3376c2b020265137f9ce2c387669ca5cfecd7d60494275c2387db5114) (and powerpc/powerpc64 by this PR) currently have ui tests for them.  I plan to add tests for other arches later.

Starting with RISC-V and s390x, which I'm familiar with and relatively easy to check for correctness.

(Relevant rustc code are supported_types/def_regs/overlapping_regs in [compiler/rustc_target/src/asm/riscv.rs](588a420350/compiler/rustc_target/src/asm/riscv.rs) and [compiler/rustc_target/src/asm/s390x.rs](588a420350/compiler/rustc_target/src/asm/s390x.rs).)

r? workingjubilee

`@rustbot` label +A-inline-assembly
2024-11-03 15:24:57 -08:00
dianne
d7d6238b23 use backticks instead of single quotes when reporting "use of unstable library feature"
This is consistent with all other diagnostics I could find containing
features and enables the use of `DiagSymbolList` for generalizing
diagnostics for unstable library features to multiple features.
2024-11-03 13:55:52 -08:00
Michael Goulet
6b96103bf3 Rename the FIXMEs, remove a few that dont matter anymore 2024-11-03 18:59:41 +00:00
Michael Goulet
0b5ddf30eb Yeet effects feature 2024-11-03 18:59:31 +00:00
Esteban Küber
e26ad8b67d Properly suggest E::assoc when we encounter E::Variant::assoc
Use the right span when encountering an enum variant followed by an associated item so we don't lose the associated item in the resulting code.

Do not suggest the thing twice, once as a removal of the associated item and a second time as a typo suggestion.
2024-11-03 18:55:19 +00:00
Michael Goulet
ace9e4c078 Gate checking ~const bounds on const_trait_impl 2024-11-03 18:48:24 +00:00
Esteban Küber
06fc531c96 Add test for assoc fn suggestion on enum variant 2024-11-03 17:15:22 +00:00
Matthias Krüger
1a0ab892cd
Rollup merge of #132528 - compiler-errors:fallback-sugg-opt, r=jieyouxu
Use `*_opt` typeck results fns to not ICE in fallback suggestion

Self-explanatory. Fixes #132517.
2024-11-03 12:08:54 +01:00
Matthias Krüger
625264329f
Rollup merge of #132523 - ranger-ross:test-issue-117446, r=compiler-errors
Added regression test for generics index out of bounds

Added a regression test for  #117446
This ICE was fixed in Rust 1.75 but a regression test was never added.

This PR adds a UI test with a reduced version of the original bug report that does not rely on external crates.
2024-11-03 12:08:54 +01:00
Matthias Krüger
9c7cdc2352
Rollup merge of #132520 - matthiaskrgr:knobu, r=jieyouxu
NFC add known bug nr to test

r? ```````@jieyouxu```````
2024-11-03 12:08:53 +01:00
Taiki Endo
b07232d95d Move tests/ui/abi/riscv32e-registers.rs to tests/ui/asm/riscv
This also adds comments explaining the difference to bad-reg.rs.
2024-11-03 18:32:04 +09:00
bors
8ccb78e0d5 Auto merge of #125579 - Noratrieb:print-host, r=davidtwco
Add `--print host-tuple` to print host target tuple

People often parse `-vV` output to get to the host tuple, which is annoying to do. It's easier to just get it directly.

I called it "host-tuple" instead of "host" because it's clearer that it's just the target name. I'm open to different names, but I think this one is fine.

a quick GitHub search for `'^host` reveals many instances of people doing the parsing, for example:

68e0ca57cd/README.md (L369)
0e38473b0c/main.sh (L96)
8a3553b865/README.md (L625)
43f3ec3970/do.sh (L35)

needs a compiler FCP. I could also do an MCP but I think just an FCP here makes the most sense.
2024-11-02 23:04:42 +00:00
uellenberg
67a85925b1 Suggest fixing typos and let bindings at the same time
Fixes #132483
2024-11-02 14:40:37 -07:00
Noratrieb
ba481518da Add --print host-triple
People often parse `-vV` output to get to the host triple, which is
annoying to do. It's easier to just get it directly.
2024-11-02 21:29:59 +01:00
Nilstrieb
77d0b4ddfb move deployment-target tests to print-request 2024-11-02 21:29:59 +01:00
bors
b3f75cc872 Auto merge of #132147 - estebank:long-types-2, r=davidtwco
Tweak E0277 output when a candidate is available

*Follow up to #132086.*

Go from

```
error[E0277]: the trait bound `Then<Ignored<chumsky::combinator::Filter<chumsky::primitive::Any<&str, chumsky::extra::Full<EmptyErr, (), ()>>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map<impl CSTParser<'a, O>, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full<EmptyErr, (), ()>>: CSTParser<'a>` is not satisfied
 --> src/main.rs:7:50
  |
7 | fn leaf<'a, O>(parser: impl CSTParser<'a, O>) -> impl CSTParser<'a, ()> {
  |                                                  ^^^^^^^^^^^^^^^^^^^^^^ the trait `chumsky::private::ParserSealed<'_, &str, (), chumsky::extra::Full<EmptyErr, (), ()>>` is not implemented for `Then<Ignored<Filter<Any<&str, ...>, ...>, ...>, ..., ..., ..., ...>`, which is required by `Then<Ignored<chumsky::combinator::Filter<chumsky::primitive::Any<&str, chumsky::extra::Full<EmptyErr, (), ()>>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map<impl CSTParser<'a, O>, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full<EmptyErr, (), ()>>: CSTParser<'a>`
  |
  = help: the trait `chumsky::private::ParserSealed<'_, &'a str, ((), ()), chumsky::extra::Full<EmptyErr, (), ()>>` is implemented for `Then<Ignored<chumsky::combinator::Filter<chumsky::primitive::Any<&str, chumsky::extra::Full<EmptyErr, (), ()>>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map<impl CSTParser<'a, O>, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full<EmptyErr, (), ()>>`
  = help: for that trait implementation, expected `((), ())`, found `()`
  = note: required for `Then<Ignored<Filter<Any<&str, ...>, ...>, ...>, ..., ..., ..., ...>` to implement `Parser<'_, &str, ()>`
note: required for `Then<Ignored<Filter<Any<&str, ...>, ...>, ...>, ..., ..., ..., ...>` to implement `CSTParser<'a>`
 --> src/main.rs:5:16
  |
5 | impl<'a, O, T> CSTParser<'a, O> for T where T: Parser<'a, &'a str, O> {}
  |                ^^^^^^^^^^^^^^^^     ^          ---------------------- unsatisfied trait bound introduced here
  = note: the full name for the type has been written to '/home/gh-estebank/longlong/target/debug/deps/longlong-0008f9a4f2023b08.long-type-13239977239800463552.txt'
  = note: consider using `--verbose` to print the full type name to the console
  = note: the full name for the type has been written to '/home/gh-estebank/longlong/target/debug/deps/longlong-0008f9a4f2023b08.long-type-13239977239800463552.txt'
  = note: consider using `--verbose` to print the full type name to the console
```

to

```
error[E0277]: the trait bound `Then<Ignored<chumsky::combinator::Filter<chumsky::primitive::Any<&str, chumsky::extra::Full<EmptyErr, (), ()>>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map<impl CSTParser<'a, O>, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full<EmptyErr, (), ()>>: CSTParser<'a>` is not satisfied
  --> src/main.rs:7:50
   |
7  | fn leaf<'a, O>(parser: impl CSTParser<'a, O>) -> impl CSTParser<'a, ()> {
   |                                                  ^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound
...
11 |     ws.then(parser.map(|_| ()))
   |     --------------------------- return type was inferred to be `Then<Ignored<..., ...>, ..., ..., ..., ...>` here
   |
   = help: the trait `ParserSealed<'_, &_, (), Full<_, _, _>>` is not implemented for `Then<Ignored<..., ...>, ..., ..., ..., ...>`
           but trait `ParserSealed<'_, &'a _, ((), ()), Full<_, _, _>>` is implemented for it
   = help: for that trait implementation, expected `((), ())`, found `()`
   = note: required for `Then<Ignored<..., ...>, ..., ..., ..., ...>` to implement `Parser<'_, &str, ()>`
note: required for `Then<Ignored<..., ...>, ..., ..., ..., ...>` to implement `CSTParser<'a>`
  --> src/main.rs:5:16
   |
5  | impl<'a, O, T> CSTParser<'a, O> for T where T: Parser<'a, &'a str, O> {}
   |                ^^^^^^^^^^^^^^^^     ^          ---------------------- unsatisfied trait bound introduced here
   = note: the full name for the type has been written to '/home/gh-estebank/longlong/target/debug/deps/longlong-df9d52be87eada65.long-type-1337037744507305372.txt'
   = note: consider using `--verbose` to print the full type name to the console
```

* Remove redundant wording
* Introduce trait diff highlighting logic and use it
* Fix incorrect "long type written to path" logic (can be split off)
* Point at tail expression in more cases in E0277
* Avoid long primary span labels in E0277 by moving them to a `help`

Fix #132013.

There are individual commits that can be their own PR. If the review load is too big, happy to split them off.
2024-11-02 20:22:49 +00:00
Esteban Küber
7e0d3ed951 fix tests
Paths in CI can be longer than in devs' machines.
2024-11-02 16:58:50 +00:00
Michael Goulet
82f8b8f0e3 Use opt functions to not ICE in fallback suggestion 2024-11-02 15:25:12 +00:00
Jieyou Xu
5596a592e3 Adjust tests to use minicore and rebless 2024-11-02 21:59:27 +08:00
Taiki Endo
e97ba53879 Add bad-reg inline assembly ui test for RISC-V and s390x 2024-11-02 21:37:03 +08:00
ranger-ross
b9196757a0
Added regression test for 117446 2024-11-02 22:17:46 +09:00
Matthias Krüger
f341a19366 NFC add known bug nr to test 2024-11-02 13:33:39 +01:00
Taiki Endo
d19517dcd0 Support clobber_abi and vector registers (clobber-only) in PowerPC inline assembly 2024-11-02 20:26:08 +09:00
bors
588a420350 Auto merge of #132497 - matthiaskrgr:rollup-gaskcn0, r=matthiaskrgr
Rollup of 11 pull requests

Successful merges:

 - #131037 (Move versioned Apple LLVM targets from `rustc_target` to `rustc_codegen_ssa`)
 - #132170 (Add a Few Codegen Tests)
 - #132333 (rust_analyzer_helix.toml: add library/ manifest)
 - #132398 (Add a couple of intra-doc links to str)
 - #132411 (CI: switch dist-x86_64-musl to free runner)
 - #132453 (Also treat `impl` definition parent as transparent regarding modules)
 - #132457 (Remove needless #![feature(asm_experimental_arch)] from loongarch64 inline assembly test)
 - #132465 (refactor(config): remove FIXME statement in comment of `omit-git-hash`)
 - #132466 (Account for late-bound depth when capturing all opaque lifetimes.)
 - #132471 (Add a bunch of mailmap entries)
 - #132488 (Remove or fix some more `FIXME(async_closure)`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-11-02 08:25:59 +00:00
Matthias Krüger
30497b05cd
Rollup merge of #132488 - compiler-errors:more-fixmes-bye, r=jieyouxu
Remove or fix some more `FIXME(async_closure)`

Self-explanatory
2024-11-02 08:33:15 +01:00
Matthias Krüger
020b63aebc
Rollup merge of #132466 - cjgillot:opaque-late, r=compiler-errors
Account for late-bound depth when capturing all opaque lifetimes.

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

r? ````@compiler-errors````
2024-11-02 08:33:14 +01:00
Matthias Krüger
fa69b671a9
Rollup merge of #132453 - Urgau:non_local_defs-impl-mod-transparent, r=jieyouxu
Also treat `impl` definition parent as transparent regarding modules

This PR changes the `non_local_definitions` lint logic to also consider `impl` definition parent as transparent regarding modules.

See tests and explanation in the changes.

``````@rustbot`````` label +L-non_local_definitions
Fixes *(after beta-backport)* #132427
cc ``````@leighmcculloch``````
r? ``````@jieyouxu``````
2024-11-02 08:33:13 +01:00
bors
b5f4883a06 Auto merge of #132352 - DianQK:llvm/19.1.3, r=nikic
Update LLVM to 19.1.3

Closes #131031.

r? nikic
2024-11-02 04:59:26 +00:00
Michael Goulet
9e5e47fc32 Remove or fix some FIXME(async_closure) 2024-11-02 03:33:31 +00:00
Esteban Küber
143b072c62 Account for negative bounds in E0277 note and suggestion
Do not suggest `#[derive(Copy)]` when we wanted a `!Copy` type.

Do not say "`Copy` is not implemented for `T` but `Copy` is".

Do not talk about `Trait` having no implementations when `!Trait` was desired.
2024-11-02 03:08:04 +00:00
Esteban Küber
1a0c502183 On long E0277 primary span label, move it to a help
Long span labels don't read well.
2024-11-02 03:08:04 +00:00
Esteban Küber
092ecca5b9 Point at tail expression on rpit E0277
```
error[E0277]: the trait bound `{gen block@$DIR/gen_block_is_coro.rs:7:5: 7:8}: Coroutine` is not satisfied
  --> $DIR/gen_block_is_coro.rs:6:13
   |
LL | fn foo() -> impl Coroutine<Yield = u32, Return = ()> {
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Coroutine` is not implemented for `{gen block@$DIR/gen_block_is_coro.rs:7:5: 7:8}`
LL |     gen { yield 42 }
   |     ---------------- return type was inferred to be `{gen block@$DIR/gen_block_is_coro.rs:7:5: 7:8}` here
```

The secondary span label is new.
2024-11-02 03:08:04 +00:00
Esteban Küber
7b9105dd88 Trim output of E0277 in some cases
Remove default note for "trait is not implemented" in favor of the
more colorful diff output from the previous commit. Removes
duplicated output.
2024-11-02 03:08:04 +00:00
Esteban Küber
b7fc1a7431 Add trait diff highlighting logic and use it in E0277
When a trait is not implemented for a type, but there *is* an `impl`
for another type or different trait params, we format the output to
use highlighting in the same way that E0308 does for types.

The logic accounts for 3 cases:
- When both the type and trait in the expected predicate and the candidate are different
- When only the types are different
- When only the trait generic params are different

For each case, we use slightly different formatting and wording.
2024-11-02 03:08:04 +00:00
bors
7c7bb7dc01 Auto merge of #132470 - GuillaumeGomez:rollup-1a1mkmp, r=GuillaumeGomez
Rollup of 14 pull requests

Successful merges:

 - #131829 (Remove support for `-Zprofile` (gcov-style coverage instrumentation))
 - #132369 (style-guide: Only use the new binop heuristic for assignments)
 - #132383 (Implement suggestion for never type fallback lints)
 - #132413 (update offset_of! docs to reflect the stabilization of nesting)
 - #132438 (Remove unncessary option for default rust-analyzer setting)
 - #132439 (Add `f16` and `f128` to `invalid_nan_comparison`)
 - #132444 (rustdoc: Directly use rustc_abi instead of reexports)
 - #132445 (Cleanup attributes around unchecked shifts and unchecked negation in const)
 - #132448 (Add missing backtick)
 - #132450 (Show actual MIR when MIR building forgot to terminate block)
 - #132451 (remove some unnecessary rustc_allow_const_fn_unstable)
 - #132455 (make const_alloc_layout feature gate only about functions that are already stable)
 - #132456 (Move remaining inline assembly test files into asm directory)
 - #132459 (feat(byte_sub_ptr): unstably add ptr::byte_sub_ptr)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-11-01 21:49:15 +00:00
Luca Versari
c8b76bcf58 Emit warning when calling/declaring functions with unavailable vectors.
On some architectures, vector types may have a different ABI depending
on whether the relevant target features are enabled. (The ABI when the
feature is disabled is often not specified, but LLVM implements some
de-facto ABI.)

As discussed in rust-lang/lang-team#235, this turns out to very easily
lead to unsound code.

This commit makes it a post-monomorphization future-incompat warning to
declare or call functions using those vector types in a context in which
the corresponding target features are disabled, if using an ABI for
which the difference is relevant. This ensures that these functions are
always called with a consistent ABI.

See the [nomination comment](https://github.com/rust-lang/rust/pull/127731#issuecomment-2288558187)
for more discussion.

Part of #116558
2024-11-01 22:24:35 +01:00
Guillaume Gomez
e9e7aa8487
Rollup merge of #132448 - chengehe:master, r=Noratrieb
Add missing backtick
2024-11-02 03:08:54 +08:00
Guillaume Gomez
2896483320
Rollup merge of #132439 - tgross35:f16-f128-nan-lint, r=jieyouxu
Add `f16` and `f128` to `invalid_nan_comparison`

Currently `f32_nan` and `f64_nan` are used to provide the `invalid_nan_comparison` lint. Since we have `f16_nan` and `f128_nan`, hook these up so the new float types get the same lints.
2024-11-02 03:08:52 +08:00
Guillaume Gomez
e31a5ca1a3
Rollup merge of #132383 - compiler-errors:never-type-fallback-sugg, r=WaffleLapkin
Implement suggestion for never type fallback lints

r? ```@WaffleLapkin```

Just opening this up for vibes; it's not done yet. I'd still like to make this suggestable in a few more cases before merge:
- [x] Try to annotate `_` -> `()`
- [x] Try to annotate local variables if they're un-annotated: `let x = ...` -> `let x: () = ...`
- [x] Try to annotate the self type of a `Trait::method()` -> `<() as Trait>::method()`.

The only other case we may want to suggest is a missing turbofish, like `f()` -> `f::<()>()`. That may be possible, but seems overly annoying.

This partly addresses https://github.com/rust-lang/rust/issues/132358; the other half of fixing that would be to make the error message a bit better, perhaps just special casing the `?` operator 🤔 I don't think I'll do that part.
2024-11-02 03:08:51 +08:00
Camille GILLOT
e2a50de5f4 Use more minimized test. 2024-11-01 18:13:26 +00:00
Camille GILLOT
45d4465028 Account for late-bound depth when capturing all opaque lifetimes. 2024-11-01 17:03:17 +00:00
Michael Goulet
57f2e12f4a Completely deny calling functions with const conditions in MIR const check unless const_trait_impl is enabled
This will help us make sure that we never leak any conditionally const
functions into stable.
2024-11-01 16:13:30 +00:00
Michael Goulet
e319838e8d Double-check conditional constness in MIR
To prevent any conditional constness from leaking through during MIR lowering
2024-11-01 16:03:52 +00:00
Urgau
37db365948 Also treat impl definition parent as transparent regarding modules 2024-11-01 16:07:02 +01:00
chengehe
5342eb0597
Add missing backtick 2024-11-01 16:53:36 +08:00
Trevor Gross
3afbe4f9c7 Add f16 and f128 to invalid_nan_comparison
Currently `f32_nan` and `f64_nan` are used to provide the
`invalid_nan_comparison` lint. Since we have `f16_nan` and `f128_nan`,
hook these up so the new float types get the same lints.
2024-10-31 21:26:36 -05:00
Michael Goulet
df6f5841e5 And also suggest for qpaths 2024-11-01 01:46:23 +00:00
Michael Goulet
c930bba283 And locals too 2024-11-01 01:46:23 +00:00
Michael Goulet
ea4fb7c25c Suggest adding self type to method 2024-11-01 01:46:23 +00:00
Michael Goulet
41966e71bc Suggest annotations for never type fallback 2024-11-01 01:46:23 +00:00
Jubilee
6b0c8cfedc
Rollup merge of #132357 - m-ou-se:explicit-abi, r=compiler-errors
Improve missing_abi lint

This is for the migration lint for https://github.com/rust-lang/rfcs/pull/3722

It is not yet marked as an edition migration lint, because `Edition2027` doesn't exist yet.

The lint now includes a machine applicable suggestion:

```
warning: extern declarations without an explicit ABI are deprecated
 --> src/main.rs:3:1
  |
3 | extern fn a() {}
  | ^^^^^^ help: explicitly specify the C ABI: `extern "C"`
  |
```
2024-10-31 17:50:41 -07:00
Jubilee
e31988cfc9
Rollup merge of #132209 - compiler-errors:modifiers, r=fmease
Fix validation when lowering `?` trait bounds

Pass the unlowered (`rustc_hir`) polarity to `lower_poly_trait_ref`.

This allows us to actually *validate* that generic args are actually valid on `?Trait` paths. This actually regressed in #113671 because that PR changed the behavior where we were inadvertently re-lowering paths as `BoundPolarity::Positive`, which was also coincidentally the only place we were enforcing the generics on `?Trait` paths were correct.
2024-10-31 17:50:40 -07:00
Jubilee
a43492b884
Rollup merge of #131168 - madsmtm:target-info-psx-os, r=davidtwco
Fix `target_os` for `mipsel-sony-psx`

Previously set to `target_os = "none"` and `target_env = "psx"` in [the PR introducing the target](https://github.com/rust-lang/rust/pull/102689/), but although the Playstation 1 is _close_ to a bare metal target in some regards, it's still very much an operating system, so we should instead set `target_os = "psx"`.

This also matches the `mipsel-sony-psp` target, which sets `target_os = "psp"`.

CC target maintainer ``@ayrtonm.``

If there's any code out there that uses `cfg(target_env = "psx")`, they can use `cfg(any(target_os = "psx", target_env = "psx"))` until they bump their MSRV to a version where this is fully fixed.
2024-10-31 17:50:40 -07:00
bors
a0d98ff0e5 Auto merge of #132356 - jieyouxu:unsound-simplify_aggregate_to_copy, r=cjgillot,DianQK
Mark `simplify_aggregate_to_copy` mir-opt as unsound

Mark the `simplify_aggregate_to_copy` mir-opt added in #128299 as unsound as it seems to miscompile the MCVE reported in https://github.com/rust-lang/rust/issues/132353. The mir-opt can be re-enabled once this case is fixed.

```rs
fn pop_min(mut score2head: Vec<Option<usize>>) -> Option<usize> {
    loop {
        if let Some(col) = score2head[0] {
            score2head[0] = None;
            return Some(col);
        }
    }
}

fn main() {
    let min = pop_min(vec![Some(1)]);
    println!("min: {:?}", min);
    // panic happens here on beta in release mode
    // but not in debug mode
    min.unwrap();
}
```

This MCVE is included as a `run-pass` ui regression test in the first commit. I built the ui test with a nightly manually, and can reproduce the behavioral difference with `-C opt-level=0` and `-C opt-level=1`. Locally, this ui test will fail unless it was run on a compiler built with the second commit marking the mir-opt as unsound thus disabling it by default.

This PR **partially reverts** commit e7386b3, reversing changes made to 02b1be1. The mir-opt implementation is just marked as unsound but **not** reverted to make reland reviews easier. Test changes are **reverted if they were not pure additions**. Tests added by the original PR received `-Z unsound-mir-opts` compile-flags.

cc `@DianQK` `@cjgillot` (PR author and reviewer of #128299)
2024-10-31 15:29:14 +00:00
Kajetan Puchalski
10edeea4b4 rustc_codegen_llvm: Add a new 'pc' option to branch-protection
Add a new 'pc' option to -Z branch-protection for aarch64 that
enables the use of PC as a diversifier in PAC branch protection code.

When the pauth-lr target feature is enabled in combination
with -Z branch-protection=pac-ret,pc, the new 9.5-a instructions
(pacibsppc, retaasppc, etc) will be generated.
2024-10-31 11:59:17 +00:00
许杰友 Jieyou Xu (Joe)
adb6d4752f tests: use minicore in tests/ui/abi/compatibility.rs as an example 2024-10-31 18:20:11 +08:00
许杰友 Jieyou Xu (Joe)
0bbe07e8ff tests/ui: add minicore compiletest self-test 2024-10-31 18:20:11 +08:00
Mara Bos
a433ea2518 Update tests. 2024-10-31 10:55:45 +01:00
许杰友 Jieyou Xu (Joe)
0d5cc8ee96 tests: ignore-debug -> ignore-std-debug-assertions 2024-10-31 17:33:42 +08:00
bors
4d296eabe4 Auto merge of #132384 - matthiaskrgr:rollup-0ze5wc4, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #132347 (Remove `ValueAnalysis` and `ValueAnalysisWrapper`.)
 - #132365 (pass `RUSTC_HOST_FLAGS` at once without the for loop)
 - #132366 (Do not enforce `~const` constness effects in typeck if `rustc_do_not_const_check`)
 - #132376 (Annotate `input` reference tests)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-31 06:22:57 +00:00
许杰友 Jieyou Xu (Joe)
4d8bda335e Add a regression test for #132353
To catch at least one pattern that was miscompiled. The test is a
minimization of the MCVE reported in
<https://github.com/rust-lang/rust/issues/132353>.
2024-10-31 13:12:22 +08:00
Matthias Krüger
49a76c14c4
Rollup merge of #132376 - ehuss:reference-input, r=traviscross
Annotate `input` reference tests

This adds test annotations for rules in the [input chapter](https://doc.rust-lang.org/nightly/reference/input-format.html) of the reference.
2024-10-31 06:11:58 +01:00
Matthias Krüger
39086e4290
Rollup merge of #132366 - compiler-errors:do-not-const-check, r=fee1-dead
Do not enforce `~const` constness effects in typeck if `rustc_do_not_const_check`

Fixes a slight inconsistency between HIR and MIR enforcement of `~const` :D

r? `@rust-lang/project-const-traits`
2024-10-31 06:11:58 +01:00
bors
c8b83785dc Auto merge of #131186 - compiler-errors:precise-capturing-borrowck, r=estebank
Try to point out when edition 2024 lifetime capture rules cause borrowck issues

Lifetime capture rules in 2024 are modified to capture more lifetimes, which sometimes lead to some non-local borrowck errors. This PR attempts to link these back together with a useful note pointing out the capture rule changes.

This is not a blocking concern, but I'd appreciate feedback (though, again, I'd like to stress that I don't want to block this PR on this): I'm worried about this note drowning in the sea of other diagnostics that borrowck emits. I was tempted to change the level of the note to `.span_warn` just so it would show up in a different color. Thoughts?

Fixes #130545

Opening as a draft first since it's stacked on #131183.
r? `@ghost`
2024-10-31 03:36:06 +00:00
Michael Goulet
c1457798db Try to point out when edition 2024 lifetime capture rules cause borrowck issues 2024-10-31 01:35:14 +00:00
bors
75eff9a574 Auto merge of #132377 - matthiaskrgr:rollup-3p1c6hs, r=matthiaskrgr
Rollup of 3 pull requests

Successful merges:

 - #132368 (Remove `do_not_const_check` from `Iterator` methods)
 - #132373 (Make sure `type_param_predicates` resolves correctly for RPITIT)
 - #132374 (Remove dead code stemming from the old effects desugaring)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-31 00:46:22 +00:00
Matthias Krüger
efd5645e43
Rollup merge of #132373 - compiler-errors:rpitit-bound, r=fmease
Make sure `type_param_predicates` resolves correctly for RPITIT

After #132194, we end up lowering the item bounds for an RPITIT in an `ItemCtxt` whose def id is the *synthetic GAT*, not the opaque type from the HIR.

This means that when we're resolving a shorthand projection like `T::Assoc`, we call the `type_param_predicates` function with the `item_def_id` of the *GAT* and not the opaque. That function operates on the HIR, and is not designed to work with the `Node::Synthetic` that gets fed for items synthesized by the compiler...

This PR reuses the trick we use elsewhere in lowering, where we intercept whether an item comes from RPITIT lowering, and forwards the query off to the correct item.

Fixes #132372
2024-10-31 01:14:03 +01:00
Michael Goulet
06a49b609f Validate associated type bounds on ? 2024-10-31 00:09:52 +00:00
Eric Huss
37c3884152 Annotate input reference tests 2024-10-30 16:47:47 -07:00
Michael Goulet
e356279bdf Actually do validation for poly trait refs with ? modifier 2024-10-30 23:42:50 +00:00
Michael Goulet
d53ca63453 Make sure type_param_predicates resolves correctly for RPITIT 2024-10-30 22:30:28 +00:00
Jubilee
847b6fe6b0
Rollup merge of #132246 - workingjubilee:campaign-on-irform, r=compiler-errors
Rename `rustc_abi::Abi` to `BackendRepr`

Remove the confabulation of `rustc_abi::Abi` with what "ABI" actually means by renaming it to `BackendRepr`, and rename `Abi::Aggregate` to `BackendRepr::Memory`. The type never actually represented how things are passed, as that has to have `PassMode` considered, at minimum, but rather it just is how we represented some things to the backend. This conflation arose because LLVM, the primary backend at the time, would lower certain IR forms using certain ABIs. Even that only somewhat was true, as it broke down when one ventured significantly afield of what is described by the System V AMD64 ABI either by using different architectures, ABI-modifying IR annotations, the same architecture **with different ISA extensions enabled**, or other... unexpected delights.

Unfortunately both names are still somewhat of a misnomer right now, as people have written code for years based on this misunderstanding. Still, their original names are even moreso, and for better or worse, this backend code hasn't received as much maintenance as the rest of the compiler, lately. Actually arriving at a correct end-state will simply require us to disentangle a lot of code in order to fix, much of it pointlessly repeated in several places. Thus this is not an "actual fix", just a way to deflect further misunderstandings.
2024-10-30 14:01:37 -07:00
Jubilee
6b60f03f15
Rollup merge of #129383 - cjgillot:opaque-noremap, r=compiler-errors,petrochenkov
Remap impl-trait lifetimes on HIR instead of AST lowering

Current AST->HIR lowering goes out of its way to remap lifetimes for opaque types. This is complicated and leaks into upstream and downstream code.

This PR stops trying to be clever during lowering, and prefers to do this remapping during the HIR->ty lowering. The remapping computation easily fits into the bound var resolution code. Its result can be used in by `generics_of` and `hir_ty_lowering::new_opaque` to add the proper parameters and arguments.

See an example on the doc for query `opaque_captured_lifetimes`.

Based on https://github.com/rust-lang/rust/pull/129244/

Fixes https://github.com/rust-lang/rust/issues/125249
Fixes https://github.com/rust-lang/rust/issues/126850

cc `@compiler-errors` `@spastorino`
r? `@petrochenkov`
2024-10-30 14:01:36 -07:00
Michael Howell
12dc24f460 rustdoc-search: simplify rules for generics and type params
This commit is a response to feedback on the displayed type
signatures results, by making generics act stricter.

Generics are tightened by making order significant. This means
`Vec<Allocator>` now matches only with a true vector of allocators,
instead of matching the second type param. It also makes unboxing
within generics stricter, so `Result<A, B>` only matches if `B`
is in the error type and `A` is in the success type. The top level
of the function search is unaffected.

Find the discussion on:

* <https://rust-lang.zulipchat.com/#narrow/stream/393423-t-rustdoc.2Fmeetings/topic/meeting.202024-07-08/near/449965149>
* <https://github.com/rust-lang/rust/pull/124544#issuecomment-2204272265>
* <https://rust-lang.zulipchat.com/#narrow/channel/266220-t-rustdoc/topic/deciding.20on.20semantics.20of.20generics.20in.20rustdoc.20search/near/476841363>
2024-10-30 12:27:48 -07:00
Michael Goulet
ec033e5bf1 Do not enforce ~const constness effects in typeck if rustc_do_mot_const_check 2024-10-30 17:41:09 +00:00
Camille GILLOT
2d74d8f333 Actually capture all in-scope lifetimes. 2024-10-30 16:22:23 +00:00
Camille GILLOT
8f6e0a6a4b Promote test. 2024-10-30 16:22:14 +00:00
Camille GILLOT
d693e19268 Promote crashes tests to ui. 2024-10-30 16:19:53 +00:00
Camille GILLOT
b6e1214ac0 Remap impl-trait lifetimes on HIR instead of AST lowering. 2024-10-30 16:18:50 +00:00
Michael Goulet
9785c7cf94 Enforce that raw lifetime identifiers must be valid raw identifiers 2024-10-30 14:45:22 +00:00
DianQK
416017d2de
Add a regression test for #131031
The failure output is:
```
SplitVectorOperand Op #1: t51: i32 = llvm.wasm.alltrue TargetConstant:i32<12408>, t50

rustc-LLVM ERROR: Do not know how to split this operator's operand!
```
2024-10-30 22:34:45 +08:00
许杰友 Jieyou Xu (Joe)
8d9686efc2
Rollup merge of #130098 - adetaylor:arbitrary-self-types-block-generics, r=wesleywiser
Reject generic self types.

The RFC for arbitrary self types v2 declares that we should reject "generic" self types. This commit does so.

The definition of "generic" was unclear in the RFC, but has been explored in
https://github.com/rust-lang/rust/issues/129147
and the conclusion is that "generic" means any `self` type which is a type parameter defined on the method itself, or references to such a type.

This approach was chosen because other definitions of "generic" don't work. Specifically,
* we can't filter out generic type _arguments_, because that would filter out Rc<Self> and all the other types of smart pointer we want to support;
* we can't filter out all type params, because Self itself is a type param, and because existing Rust code depends on other type params declared on the type (as opposed to the method).

This PR decides to make a new error code for this case, instead of reusing the existing E0307 error. This makes the code a bit more complex, but it seems we have an opportunity to provide specific diagnostics for this case so we should do so.

This PR filters out generic self types whether or not the 'arbitrary self types' feature is enabled. However, it's believed that it can't have any effect on code which uses stable Rust, since there are no stable traits which can be used to indicate a valid generic receiver type, and thus it would have been impossible to write code which could trigger this new error case. It is however possible that this could break existing code which uses either of the unstable `arbitrary_self_types` or `receiver_trait` features. This breakage is intentional; as we move arbitrary self types towards stabilization we don't want to continue to support generic such types.

This PR adds lots of extra tests to arbitrary-self-from-method-substs. Most of these are ways to trigger a "type mismatch" error which 9b82580c73/compiler/rustc_hir_typeck/src/method/confirm.rs (L519) hopes can be minimized by filtering out generics in this way. We remove a FIXME from confirm.rs suggesting that we make this change. It's still possible to cause type mismatch errors, and a subsequent PR may be able to improve diagnostics in this area, but it's harder to cause these errors without contrived uses of the turbofish.

This is a part of the arbitrary self types v2 project, https://github.com/rust-lang/rfcs/pull/3519
https://github.com/rust-lang/rust/issues/44874

r? `@wesleywiser`
2024-10-30 22:22:02 +08:00
Adrian Taylor
6d8d79595e Reject generic self types.
The RFC for arbitrary self types v2 declares that we should reject
"generic" self types. This commit does so.

The definition of "generic" was unclear in the RFC, but has been
explored in
https://github.com/rust-lang/rust/issues/129147
and the conclusion is that "generic" means any `self` type which
is a type parameter defined on the method itself, or references
to such a type.

This approach was chosen because other definitions of "generic"
don't work. Specifically,
* we can't filter out generic type _arguments_, because that would
  filter out Rc<Self> and all the other types of smart pointer
  we want to support;
* we can't filter out all type params, because Self itself is a
  type param, and because existing Rust code depends on other
  type params declared on the type (as opposed to the method).

This PR decides to make a new error code for this case, instead of
reusing the existing E0307 error. This makes the code a
bit more complex, but it seems we have an opportunity to provide
specific diagnostics for this case so we should do so.

This PR filters out generic self types whether or not the
'arbitrary self types' feature is enabled. However, it's believed
that it can't have any effect on code which uses stable Rust, since
there are no stable traits which can be used to indicate a valid
generic receiver type, and thus it would have been impossible to
write code which could trigger this new error case.
It is however possible that this could break existing code which
uses either of the unstable `arbitrary_self_types` or
`receiver_trait` features. This breakage is intentional; as
we move arbitrary self types towards stabilization we don't want
to continue to support generic such types.

This PR adds lots of extra tests to arbitrary-self-from-method-substs.
Most of these are ways to trigger a "type mismatch" error which
9b82580c73/compiler/rustc_hir_typeck/src/method/confirm.rs (L519)
hopes can be minimized by filtering out generics in this way.
We remove a FIXME from confirm.rs suggesting that we make this change.
It's still possible to cause type mismatch errors, and a subsequent
PR may be able to improve diagnostics in this area, but it's harder
to cause these errors without contrived uses of the turbofish.

This is a part of the arbitrary self types v2 project,
https://github.com/rust-lang/rfcs/pull/3519
https://github.com/rust-lang/rust/issues/44874

r? @wesleywiser
2024-10-30 10:48:08 +00:00
bors
298c7462c3 Auto merge of #130860 - tmandry:fix-directives, r=jieyouxu
Fix directives for lint-non-snake-case-crate

This test fails on targets without unwinding or with `--target-rustcflags=-Cpanic=abort` because the proc macro was compiled as the target, not the host. Some targets were explicitly disabled to pass CI, but these directives are more general.

* `needs-dynamic-linking` is self explanatory
* `force-host` for proc macros
* `no-prefer-dynamic` is apparently also used for proc macros

Note that `needs-unwind` can also be useful for situations other than proc macros where unwinding is necessary.

r? `@jieyouxu`

try-job: test-various
2024-10-30 10:28:56 +00:00
Jubilee Young
083a362dd1 tests: Bless rustc_abi::Abi::Aggregate => ::Memory 2024-10-30 01:41:31 -07:00
Jubilee Young
0b9d1eb889 tests: cross-compile multi-platform ZST ABI tests
This allows them to be blessed, regardless of platform.
2024-10-30 01:41:27 -07:00
Matthias Krüger
2480e3bbc5
Rollup merge of #132332 - nnethercote:use-token_descr-more, r=estebank
Use `token_descr` more in error messages

This is the first two commits from #124141, put into their own PR to get things rolling. Commit messages have the details.

r? ``@estebank``
cc ``@petrochenkov``
2024-10-30 06:40:36 +01:00
Matthias Krüger
87d348b333
Rollup merge of #129394 - Jarcho:irrefutable_let_patterns, r=Nadrieril
Don't lint `irrefutable_let_patterns` on leading patterns if `else if` let-chains

fixes #128661

Is there any preference where the test goes? There looks to be several places it could fit.
2024-10-30 06:40:34 +01:00
Michael Goulet
1990f15608 Reject raw lifetime followed by \' as well 2024-10-30 01:13:18 +00:00
Tyler Mandry
d942113fdb Fix directives for lint-non-snake-case-crate
This test fails on targets without unwinding because the proc macro was
compiled as the target, not the host. Some targets were explicitly
disabled to pass CI, but these directives are more general.

Fixes Fuchsia tests.
2024-10-29 16:40:06 -07:00
Jason Newcomb
4a2e08af22 Don't lint irrefutable_let_patterns on leading patterns if else if let-chains. 2024-10-29 14:43:50 -04:00
Matthias Krüger
f9fdd63cf4
Rollup merge of #132157 - estebank:long-types-3, r=jieyouxu
Remove detail from label/note that is already available in other note

Remove the "which is required by `{root_obligation}`" post-script in
"the trait `X` is not implemented for `Y`" explanation in E0277. This
information is already conveyed in the notes explaining requirements,
making it redundant while making the text (particularly in labels)
harder to read.

```
error[E0277]: the trait bound `NotCopy: Copy` is not satisfied
  --> $DIR/wf-static-type.rs:10:13
   |
LL | static FOO: IsCopy<Option<NotCopy>> = IsCopy { t: None };
   |             ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`
   |
   = note: required for `Option<NotCopy>` to implement `Copy`
note: required by a bound in `IsCopy`
  --> $DIR/wf-static-type.rs:7:17
   |
LL | struct IsCopy<T:Copy> { t: T }
   |                 ^^^^ required by this bound in `IsCopy`
```
vs the prior

```
error[E0277]: the trait bound `NotCopy: Copy` is not satisfied
  --> $DIR/wf-static-type.rs:10:13
   |
LL | static FOO: IsCopy<Option<NotCopy>> = IsCopy { t: None };
   |             ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`, which is required by `Option<NotCopy>: Copy`
   |
   = note: required for `Option<NotCopy>` to implement `Copy`
note: required by a bound in `IsCopy`
  --> $DIR/wf-static-type.rs:7:17
   |
LL | struct IsCopy<T:Copy> { t: T }
   |                 ^^^^ required by this bound in `IsCopy`
```

*Ignore first three commits from https://github.com/rust-lang/rust/pull/132086.*
2024-10-29 18:38:58 +01:00
Matthias Krüger
5dc36391fe
Rollup merge of #132151 - compiler-errors:coroutine-resume-outlives, r=spastorino
Ensure that resume arg outlives region bound for coroutines

When proving that `{Coroutine}: 'region`, we must also prove that the coroutine's resume ty outlives that region as well. See the inline comment.

Fixes #132104
2024-10-29 18:38:57 +01:00
Matthias Krüger
5d6c49938e
Rollup merge of #131984 - dingxiangfei2009:stabilize-if-let-rescope, r=traviscross,lcnr
Stabilize if_let_rescope

Close #131154
Tracked by #124085
2024-10-29 18:38:57 +01:00
Esteban Küber
5b54286640 Remove detail from label/note that is already available in other note
Remove the "which is required by `{root_obligation}`" post-script in
"the trait `X` is not implemented for `Y`" explanation in E0277. This
information is already conveyed in the notes explaining requirements,
making it redundant while making the text (particularly in labels)
harder to read.

```
error[E0277]: the trait bound `NotCopy: Copy` is not satisfied
  --> $DIR/wf-static-type.rs:10:13
   |
LL | static FOO: IsCopy<Option<NotCopy>> = IsCopy { t: None };
   |             ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`
   |
   = note: required for `Option<NotCopy>` to implement `Copy`
note: required by a bound in `IsCopy`
  --> $DIR/wf-static-type.rs:7:17
   |
LL | struct IsCopy<T:Copy> { t: T }
   |                 ^^^^ required by this bound in `IsCopy`
```
vs the prior

```
error[E0277]: the trait bound `NotCopy: Copy` is not satisfied
  --> $DIR/wf-static-type.rs:10:13
   |
LL | static FOO: IsCopy<Option<NotCopy>> = IsCopy { t: None };
   |             ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`, which is required by `Option<NotCopy>: Copy`
   |
   = note: required for `Option<NotCopy>` to implement `Copy`
note: required by a bound in `IsCopy`
  --> $DIR/wf-static-type.rs:7:17
   |
LL | struct IsCopy<T:Copy> { t: T }
   |                 ^^^^ required by this bound in `IsCopy`
```
2024-10-29 16:26:57 +00:00
Jubilee
b8f08fe023
Rollup merge of #132194 - compiler-errors:rpitit-super-wc, r=spastorino
Collect item bounds for RPITITs from trait where clauses just like associated types

We collect item bounds from trait where clauses for *associated types*, i.e. this:

```rust
trait Foo
where
    Self::Assoc: Send
{
    type Assoc;
}
```

Becomes this:

```rust
trait Foo {
    type Assoc: Send;
}
```

Today, with RPITITs/AFIT and return-type notation, we don't do that, i.e.:

```rust
trait Foo where Self::method(..): Send {
    fn method() -> impl Sized;
}

fn is_send(_: impl Send) {}
fn test<T: Foo>() {
    is_send(T::method());
}
```

...which fails on nightly today.

 Turns out it's super easy to fix this, and we just need to use the `associated_type_bounds` lowering function in `explicit_item_bounds_with_filter`, which has that logic baked in.
2024-10-29 03:11:41 -07:00
Jubilee
e97286e738
Rollup merge of #132119 - compiler-errors:effects-old-solver, r=lcnr
Hack out effects support for old solver

Opening this for vibes 

Turns out that a basic, somewhat incomplete implementation of host effects is achievable in the old trait solver pretty easily. This should be sufficient for us to use in the standard library itself.

Regarding incompleteness, maybe we should always treat host predicates as ambiguous in intercrate mode (at least in the old solver) to avoid any worries about accidental impl overlap or something.

r? ```@lcnr``` cc ```@fee1-dead```
2024-10-29 03:11:40 -07:00
bors
2df8dbb1b3 Auto merge of #132277 - workingjubilee:rollup-5e6q6e4, r=workingjubilee
Rollup of 9 pull requests

Successful merges:

 - #130259 (Lower AST node id only once)
 - #131441 (Add a new trait `proc_macro::ToTokens`)
 - #132247 (stable_mir: Directly use types from rustc_abi)
 - #132249 (compiler: Add rustc_abi dependence to the compiler)
 - #132255 (Add `LayoutData::is_uninhabited` and use it)
 - #132258 ([rustdoc] Unify variant struct fields margins with struct fields)
 - #132260 (cg_llvm: Use a type-safe helper to cast `&str` and `&[u8]` to `*const c_char`)
 - #132261 (refactor: cleaner check to return None)
 - #132271 (Updating Fuchsia platform-support documentation)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-29 07:32:45 +00:00
Yuri Astrakhan
a645342720 More test for non-exhaustive C-like enums in FFI
Add a few more possibly false-positive tests for the `improper_ctypes` lint
2024-10-28 23:05:45 -04:00
bors
a9d17627d2 Auto merge of #128985 - GrigorenkoPV:instantly-dangling-pointer, r=Urgau
Lint against getting pointers from immediately dropped temporaries

Fixes #123613

## Changes:
1. New lint: `dangling_pointers_from_temporaries`. Is a generalization of `temporary_cstring_as_ptr` for more types and more ways to get a temporary.
2. `temporary_cstring_as_ptr` is removed and marked as renamed to `dangling_pointers_from_temporaries`.
3. `clippy::temporary_cstring_as_ptr` is marked as renamed to `dangling_pointers_from_temporaries`.
4. Fixed a false positive[^fp] for when the pointer is not actually dangling because of lifetime extension for function/method call arguments.
5. `core::cell::Cell` is now `rustc_diagnostic_item = "Cell"`

## Questions:
- [ ]  Instead of manually checking for a list of known methods and diagnostic items, maybe add some sort of annotation to those methods in library and check for the presence of that annotation? https://github.com/rust-lang/rust/pull/128985#issuecomment-2318714312

## Known limitations:

### False negatives[^fn]:

See the comments in `compiler/rustc_lint/src/dangling.rs`

1. Method calls that are not checked for:
   - `temporary_unsafe_cell.get()`
   - `temporary_sync_unsafe_cell.get()`
2. Ways to get a temporary that are not recognized:
   - `owning_temporary.field`
   - `owning_temporary[index]`
3. No checks for ref-to-ptr conversions:
   - `&raw [mut] temporary`
   - `&temporary as *(const|mut) _`
    - `ptr::from_ref(&temporary)` and friends

[^fn]: lint **should** be emitted, but **is not**

[^fp]: lint **should not** be emitted, but **is**
2024-10-29 00:24:07 +00:00
Michael Goulet
8b7b8e5f56 Hack out effects support for old solver 2024-10-28 21:42:14 +00:00
Jubilee
a24b3778d6
Rollup merge of #130259 - adwinwhite:lower-node-id-once, r=cjgillot
Lower AST node id only once

Fixes #96346.

I basically followed the given instructions except the inline part.

`lower_jump_destination` can't reuse local existing `HirId` due to unknown name resolution result so I created an additional mapping for labels.

r? ```@cjgillot```
2024-10-28 10:18:48 -07:00
bors
3f1be1ec7e Auto merge of #132145 - RalfJung:stdarch, r=Amanieu
bump stdarch

This lets us remove a hack from https://github.com/rust-lang/rust/pull/131349.

r? `@Amanieu`

try-job: test-various
2024-10-28 16:25:56 +00:00
Alex Crichton
f534974037 Add a new wide-arithmetic feature for WebAssembly
This commit adds a new rustc target feature named `wide-arithmetic` for
WebAssembly targets. This corresponds to the [wide-arithmetic] proposal
for WebAssembly which adds new instructions catered towards accelerating
integer arithmetic larger than 64-bits. This proposal to WebAssembly is
not standard yet so this new feature is flagged as an unstable target
feature. Additionally Rust's LLVM version doesn't support this new
feature yet since support will first be added in LLVM 20, so the
feature filtering logic for LLVM is updated to handle this.

I'll also note that I'm not currently planning to add wasm-specific
intrinsics to `std::arch::wasm32` at this time. The currently proposed
instructions are all accessible through `i128` or `u128`-based
operations which Rust already supports, so intrinsic shouldn't be
necessary to get access to these new instructions.

[wide-arithmetic]: https://github.com/WebAssembly/wide-arithmetic
2024-10-28 08:11:47 -07:00
bors
9f57edf2e2 Auto merge of #132262 - matthiaskrgr:rollup-pcphi6l, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #131391 (Stabilize `isqrt` feature)
 - #132248 (rustc_transmute: Directly use types from rustc_abi)
 - #132252 (compiler: rename LayoutS to LayoutData)
 - #132253 (Known-bug test for `keyword_idents` lint not propagating to other files)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-28 13:32:57 +00:00
Pavel Grigorenko
c69894eaec New lint: dangling_pointers_from_temporaries 2024-10-28 14:16:05 +03:00
Matthias Krüger
2ca9b2cddd
Rollup merge of #132253 - Zalathar:keyword-idents-bug, r=jieyouxu
Known-bug test for `keyword_idents` lint not propagating to other files

Known-bug test for `keyword_idents` lint not propagating to other files when configured via attribute (#132218).
2024-10-28 12:14:59 +01:00
Ralf Jung
d066dfdb83 we can now enable the 'const stable fn must be stable' check 2024-10-28 11:48:39 +01:00
bors
32b17d56eb Auto merge of #132244 - jyn514:linker-refactors, r=bjorn3
fix various linker warnings

separated out from https://github.com/rust-lang/rust/pull/119286; this doesn't have anything user-facing, i just want to land these changes so i can stop rebasing them.

r? `@bjorn3`
2024-10-28 10:44:24 +00:00
Adwin White
cb08e08722 Lower AST node id only once 2024-10-28 14:12:17 +08:00
Zalathar
dfafbc41d8 Known-bug test for keyword_idents lint not propagating to other files 2024-10-28 16:57:08 +11:00
许杰友 Jieyou Xu (Joe)
3e3feac7c3
Rollup merge of #132243 - compiler-errors:no-span, r=jieyouxu
Remove `ObligationCause::span()` method

I think it's an incredibly confusing footgun to expose both `obligation_cause.span` and `obligation_cause.span()`. Especially because `ObligationCause::span()` (the method) seems to just be hacking around a single quirk in the way we set up obligation causes for match arms.

First commit removes the need for that hack, with only one diagnostic span changing (but IMO not really getting worse -- I'd argue that it was already confusing).
2024-10-28 13:36:21 +08:00
许杰友 Jieyou Xu (Joe)
a9ee1d025b
Rollup merge of #132227 - compiler-errors:better-const-span, r=Nadrieril
Pass constness with span into lower_poly_trait_ref

Gives us a span to point at for ~const/const on non-const traits.

Split from #132209. r? Nadrieril
2024-10-28 13:36:20 +08:00
许杰友 Jieyou Xu (Joe)
20d2a546fa
Rollup merge of #132086 - estebank:long-types, r=jieyouxu
Tweak E0277 highlighting and "long type" path printing

Partially address #132013.

![Output from this PR for the repro case in #132013](https://github.com/user-attachments/assets/a073ba37-4adc-411e-81f7-6cb9a945ce3d)
2024-10-28 13:36:18 +08:00
asquared31415
6fc7ce43d2 Error on alignments greater than isize::MAX
Co-authored-by: Jieyou Xu <jieyouxu@outlook.com>
2024-10-28 13:17:37 +08:00
Nicholas Nethercote
dd2b027d5d Tweak more warnings.
Much like the previous commit.

I think the removal of "the token" in each message is fine here. There
are many more error messages that mention tokens without saying "the
token" than those that do say it.
2024-10-28 14:20:28 +11:00
Nicholas Nethercote
a201fab208 Tweak expand_incomplete_parse warning.
By using `token_descr`, as is done for many other errors, we can get
slightly better descriptions in error messages, e.g.
"macro expansion ignores token `let` and any following" becomes
"macro expansion ignores keyword `let` and any tokens following".

This will be more important once invisible delimiters start being
mentioned in error messages -- without this commit, that leads to error
messages such as "error at ``" because invisible delimiters are
pretty printed as an empty string.
2024-10-28 14:12:45 +11:00
jyn
f1e5b365f0 port tests/ui/linkage-attr/framework to run-make
this makes it much easier to understand test failures.

before:
```
diff of stderr:

1 error: linking with `LINKER` failed: exit status: 1
2    |
-            ld: Undefined symbols:
4              _CFRunLoopGetTypeID, referenced from:
5            clang: error: linker command failed with exit code 1 (use -v to see invocation)
```

after:
```
=== HAYSTACK ===
error: linking with `cc` failed: exit status: 1
  |
  = note: use `--verbose` to show all linker arguments
  = note: Undefined symbols for architecture arm64:
            "_CFRunLoopGetTypeID", referenced from:
                main::main::hbb553f5dda62d3ea in main.main.d17f5fbe6225cf88-cgu.0.rcgu.o
          ld: symbol(s) not found for architecture arm64
          clang: error: linker command failed with exit code 1 (use -v to see invocation)

error: aborting due to 1 previous error

=== NEEDLE ===
_CFRunLoopGetTypeID\.?, referenced from:
thread 'main' panicked at /Users/jyn/git/rust-lang/rust/tests/run-make/linkage-attr-framework/rmake.rs:22:10:
needle was not found in haystack
```

this also fixes a failure related to missing whitespace; we don't actually care about whitespace in this test.
2024-10-27 21:23:28 -04:00
Michael Goulet
2507e83d7b Stop using the whole match expr span for an arm's obligation span 2024-10-27 22:48:03 +00:00
bors
df4ca44d3f Auto merge of #132237 - matthiaskrgr:rollup-ulogwtd, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #132043 (Simplify param handling in `resolve_bound_vars`)
 - #132214 (Cleanup: Move an impl-Trait check from AST validation to AST lowering)
 - #132221 (Clean up some comments on lint implementation)
 - #132228 (Revert "ci update freebsd version proposal, freebsd 12 being eol.")
 - #132234 (Miri subtree update)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-27 20:00:19 +00:00
Matthias Krüger
574a8ba6af
Rollup merge of #132214 - fmease:mv-impl-trait-val-paths, r=compiler-errors
Cleanup: Move an impl-Trait check from AST validation to AST lowering

Namely the one that rejects `impl Trait` in qself types and non-final path segments.
There's no good reason to perform this during AST validation.
We have better infrastructure in place in the AST lowerer (`ImplTraitContext`).
This shaves off a lot of code.
We now lower `impl Trait` in bad positions to `{type error}` which allows us to
remove a special case from HIR ty lowering.

Coincidentally fixes #126725. Well, it only *masks* it by passing `{type error}` to HIR analysis instead of a "bad" opaque. I was able to find a new reproducer for it. See the issue.
2024-10-27 19:49:07 +01:00
bors
81d6652e74 Auto merge of #131284 - dingxiangfei2009:rename-smart-ptr-to-coerce-referent, r=compiler-errors
Rename macro `SmartPointer` to `CoercePointee`

As per resolution #129104 we will rename the macro to better reflect the technical specification of the feature and clarify the communication.

- `SmartPointer` is renamed to `CoerceReferent`
- `#[pointee]` attribute is renamed to `#[referent]`
- `#![feature(derive_smart_pointer)]` gate is renamed to `#![feature(derive_coerce_referent)]`.
- Any mention of `SmartPointer` in the file names are renamed accordingly.

r? `@compiler-errors`

cc `@nikomatsakis` `@Darksonn`
2024-10-27 17:04:12 +00:00
León Orell Valerian Liehr
442f39582d
Move an impl-Trait check from AST validation to AST lowering 2024-10-27 07:41:52 +01:00
bors
f7cf41c973 Auto merge of #131900 - mrkajetanp:target-feature-pauth-lr, r=Amanieu
rustc_target: Add pauth-lr aarch64 target feature

Add the pauth-lr target feature, corresponding to aarch64 FEAT_PAuth_LR. This feature has been added in LLVM 19.
It is currently not supported by the Linux hwcap and so we cannot add runtime feature detection for it at this time.

r? `@Amanieu`
2024-10-27 00:09:49 +00:00
Michael Goulet
bd95695b94 Pass constness with span into lower_poly_trait_ref 2024-10-26 20:54:38 +00:00
Michael Goulet
6ab87f8238 Collect item bounds for RPITITs from trait where clauses just like associated types 2024-10-26 17:38:08 +00:00
许杰友 Jieyou Xu (Joe)
50e78b8b3c
Rollup merge of #132180 - Urgau:ast_pretty-unsafe-attr, r=compiler-errors
Print unsafety of attribute in AST pretty print

This PR fixes the AST pretty print, which was missing the unsafety for unsafe attributes.

Related to https://github.com/rust-lang/rust/pull/131558#discussion_r1807736204
2024-10-26 22:01:14 +08:00
许杰友 Jieyou Xu (Joe)
bafe790a2d
Rollup merge of #132169 - fee1-dead-contrib:consttraitsck, r=compiler-errors
Deny calls to non-`#[const_trait]` methods in MIR constck

This is a (potentially temporary) fix that closes off the mismatch in assumptions between MIR constck and typeck which does the const traits checking. Before this PR, MIR constck assumed that typeck correctly handled all calls to trait methods in const contexts if effects is enabled. That is not true because typeck only correctly handles callees that are const. For non-const callees (such as methods in a non-const_trait), typeck had never created an error.

45089ec19e/compiler/rustc_hir_typeck/src/callee.rs (L876-L877)

I called this potentially temporary because the const checks could be moved to HIR entirely. Alongside the recent refactor in const stability checks where that component could be placed would need more discussion. (cc ```@compiler-errors``` ```@RalfJung)```

Tests are updated, mainly due to traits not being const in core, so tests that call them correctly error.

This fixes https://github.com/rust-lang/project-const-traits/issues/12.
2024-10-26 22:01:13 +08:00
Urgau
f5b6f938ce Print unsafety of attribute in AST unpretty 2024-10-26 13:33:36 +02:00
Urgau
f249fdd962 Add AST unpretty test for unsafe attribute 2024-10-26 13:31:24 +02:00
bors
ae4c6b6640 Auto merge of #132152 - lqd:revert-127731, r=compiler-errors
Revert #127731 "Emit error when calling/declaring functions with unavailable …"

This reverts #127731 due to the unexpected [perf regressions](https://github.com/rust-lang/rust/pull/127731#issuecomment-2438687094) and to give time to mitigate the regressions before re-landing it.

r? `@RalfJung` cc `@veluca93`
2024-10-26 04:24:31 +00:00
Deadbeef
f2f67232a5 Deny calls to non-#[const_trait] methods in MIR constck 2024-10-26 11:35:56 +08:00
bors
54761cb3e8 Auto merge of #131349 - RalfJung:const-stability-checks, r=compiler-errors
Const stability checks v2

The const stability system has served us well ever since `const fn` were first stabilized. It's main feature is that it enforces *recursive* validity -- a stable const fn cannot internally make use of unstable const features without an explicit marker in the form of `#[rustc_allow_const_fn_unstable]`. This is done to make sure that we don't accidentally expose unstable const features on stable in a way that would be hard to take back. As part of this, it is enforced that a `#[rustc_const_stable]` can only call `#[rustc_const_stable]` functions. However, some problems have been coming up with increased usage:
- It is baffling that we have to mark private or even unstable functions as `#[rustc_const_stable]` when they are used as helpers in regular stable `const fn`, and often people will rather add `#[rustc_allow_const_fn_unstable]` instead which was not our intention.
- The system has several gaping holes: a private `const fn` without stability attributes whose inherited stability (walking up parent modules) is `#[stable]` is allowed to call *arbitrary* unstable const operations, but can itself be called from stable `const fn`. Similarly, `#[allow_internal_unstable]` on a macro completely bypasses the recursive nature of the check.

Fundamentally, the problem is that we have *three* disjoint categories of functions, and not enough attributes to distinguish them:
1. const-stable functions
2. private/unstable functions that are meant to be callable from const-stable functions
3. functions that can make use of unstable const features

Functions in the first two categories cannot use unstable const features and they can only call functions from the first two categories.

This PR implements the following system:
- `#[rustc_const_stable]` puts functions in the first category. It may only be applied to `#[stable]` functions.
- `#[rustc_const_unstable]` by default puts functions in the third category. The new attribute `#[rustc_const_stable_indirect]` can be added to such a function to move it into the second category.
- `const fn` without a const stability marker are in the second category if they are still unstable. They automatically inherit the feature gate for regular calls, it can now also be used for const-calls.

Also, all the holes mentioned above have been closed. There's still one potential hole that is hard to avoid, which is when MIR building automatically inserts calls to a particular function in stable functions -- which happens in the panic machinery. Those need to be manually marked `#[rustc_const_stable_indirect]` to be sure they follow recursive const stability. But that's a fairly rare and special case so IMO it's fine.

The net effect of this is that a `#[unstable]` or unmarked function can be constified simply by marking it as `const fn`, and it will then be const-callable from stable `const fn` and subject to recursive const stability requirements. If it is publicly reachable (which implies it cannot be unmarked), it will be const-unstable under the same feature gate. Only if the function ever becomes `#[stable]` does it need a `#[rustc_const_unstable]` or `#[rustc_const_stable]` marker to decide if this should also imply const-stability.

Adding `#[rustc_const_unstable]` is only needed for (a) functions that need to use unstable const lang features (including intrinsics), or (b) `#[stable]` functions that are not yet intended to be const-stable. Adding `#[rustc_const_stable]` is only needed for functions that are actually meant to be directly callable from stable const code. `#[rustc_const_stable_indirect]` is used to mark intrinsics as const-callable and for `#[rustc_const_unstable]` functions that are actually called from other, exposed-on-stable `const fn`. No other attributes are required.

Also see the updated dev-guide at https://github.com/rust-lang/rustc-dev-guide/pull/2098.

I think in the future we may want to tweak this further, so that in the hopefully common case where a public function's const-stability just exactly mirrors its regular stability, we never have to add any attribute. But right now, once the function is stable this requires `#[rustc_const_stable]`.

### Open question

There is one point I could see we might want to do differently, and that is putting `#[rustc_const_unstable]`  functions (but not intrinsics) in category 2 by default, and requiring an extra attribute for `#[rustc_const_not_exposed_on_stable]` or so. This would require a bunch of extra annotations, but would have the advantage that turning a `#[rustc_const_unstable]` into `#[rustc_const_stable]`  will never change the way the function is const-checked. Currently, we often discover in the const stabilization PR that a function needs some other unstable const things, and then we rush to quickly deal with that. In this alternative universe, we'd work towards getting rid of the `rustc_const_not_exposed_on_stable` before stabilization, and once that is done stabilization becomes a trivial matter. `#[rustc_const_stable_indirect]` would then only be used for intrinsics.

I think I like this idea, but might want to do it in a follow-up PR, as it will need a whole bunch of annotations in the standard library. Also, we probably want to convert all const intrinsics to the "new" form (`#[rustc_intrinsic]` instead of an `extern` block) before doing this to avoid having to deal with two different ways of declaring intrinsics.

Cc `@rust-lang/wg-const-eval` `@rust-lang/libs-api`
Part of https://github.com/rust-lang/rust/issues/129815 (but not finished since this is not yet sufficient to safely let us expose `const fn` from hashbrown)
Fixes https://github.com/rust-lang/rust/issues/131073 by making it so that const-stable functions are always stable

try-job: test-various
2024-10-25 23:29:40 +00:00
Rémy Rakic
bd8477b562 Revert "Emit error when calling/declaring functions with unavailable vectors."
This reverts commit 5af56cac38.
2024-10-25 20:42:09 +00:00
Michael Goulet
ad76564900 Ensure that resume arg outlives region bound for coroutines 2024-10-25 20:16:52 +00:00
Ralf Jung
36dda4571d add a HACK to allow stdarch migration 2024-10-25 20:31:40 +02:00
Ralf Jung
a0215d8e46 Re-do recursive const stability checks
Fundamentally, we have *three* disjoint categories of functions:
1. const-stable functions
2. private/unstable functions that are meant to be callable from const-stable functions
3. functions that can make use of unstable const features

This PR implements the following system:
- `#[rustc_const_stable]` puts functions in the first category. It may only be applied to `#[stable]` functions.
- `#[rustc_const_unstable]` by default puts functions in the third category. The new attribute `#[rustc_const_stable_indirect]` can be added to such a function to move it into the second category.
- `const fn` without a const stability marker are in the second category if they are still unstable. They automatically inherit the feature gate for regular calls, it can now also be used for const-calls.

Also, several holes in recursive const stability checking are being closed.
There's still one potential hole that is hard to avoid, which is when MIR
building automatically inserts calls to a particular function in stable
functions -- which happens in the panic machinery. Those need to *not* be
`rustc_const_unstable` (or manually get a `rustc_const_stable_indirect`) to be
sure they follow recursive const stability. But that's a fairly rare and special
case so IMO it's fine.

The net effect of this is that a `#[unstable]` or unmarked function can be
constified simply by marking it as `const fn`, and it will then be
const-callable from stable `const fn` and subject to recursive const stability
requirements. If it is publicly reachable (which implies it cannot be unmarked),
it will be const-unstable under the same feature gate. Only if the function ever
becomes `#[stable]` does it need a `#[rustc_const_unstable]` or
`#[rustc_const_stable]` marker to decide if this should also imply
const-stability.

Adding `#[rustc_const_unstable]` is only needed for (a) functions that need to
use unstable const lang features (including intrinsics), or (b) `#[stable]`
functions that are not yet intended to be const-stable. Adding
`#[rustc_const_stable]` is only needed for functions that are actually meant to
be directly callable from stable const code. `#[rustc_const_stable_indirect]` is
used to mark intrinsics as const-callable and for `#[rustc_const_unstable]`
functions that are actually called from other, exposed-on-stable `const fn`. No
other attributes are required.
2024-10-25 20:31:40 +02:00
Esteban Küber
aa82fd6d1d Tweak highlighting when trait is available for different type
When printing

```
  = help: the trait `chumsky::private::ParserSealed<'_, &'a str, ((), ()), chumsky::extra::Full<EmptyErr, (), ()>>` is implemented for `Then<Ignored<chumsky::combinator::Filter<chumsky::primitive::Any<&str, chumsky::extra::Full<EmptyErr, (), ()>>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map<impl CSTParser<'a, O>, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full<EmptyErr, (), ()>>`
  = help: for that trait implementation, expected `((), ())`, found `()`
```

Highlight only the `expected` and `found` types, instead of the full type in the first `help`.
2024-10-25 18:06:39 +00:00
Esteban Küber
24ac777a64 Add test for #132013 2024-10-25 18:06:36 +00:00
bors
6faf0bd3e5 Auto merge of #127731 - veluca93:abi_checks, r=RalfJung
Emit future-incompatibility lint when calling/declaring functions with vectors that require missing target feature

On some architectures, vector types may have a different ABI depending on whether the relevant target features are enabled. (The ABI when the feature is disabled is often not specified, but LLVM implements some de-facto ABI.)

As discussed in https://github.com/rust-lang/lang-team/issues/235, this turns out to very easily lead to unsound code.

This commit makes it a post-monomorphization error to declare or call functions using those vector types in a context in which the corresponding target features are disabled, if using an ABI for which the difference is relevant. This ensures that these functions are always called with a consistent ABI.

See the [nomination comment](https://github.com/rust-lang/rust/pull/127731#issuecomment-2288558187) for more discussion.

r? RalfJung

Part of https://github.com/rust-lang/rust/issues/116558
2024-10-25 15:17:47 +00:00
Luca Versari
5af56cac38 Emit error when calling/declaring functions with unavailable vectors.
On some architectures, vector types may have a different ABI when
relevant target features are enabled.

As discussed in https://github.com/rust-lang/lang-team/issues/235, this
turns out to very easily lead to unsound code.

This commit makes it an error to declare or call functions using those
vector types in a context in which the corresponding target features are
disabled, if using an ABI for which the difference is relevant.
2024-10-25 08:46:40 +02:00
Jubilee
3c6d34f4c4
Rollup merge of #132118 - compiler-errors:tilde-const-item-bounds, r=lcnr
Add support for `~const` item bounds

Supports the only missing capability of `~const` associated types that I can think of now (this is obviously excluding `~const` opaques, which I see as an extension to this; I'll probably do that next).

r? ``@lcnr`` mostly b/c it changes candidate assembly, or reassign

cc ``@fee1-dead``
2024-10-24 23:23:56 -07:00
Michael Goulet
3bad5014c9 Add support for ~const item bounds 2024-10-24 23:43:31 +00:00
bors
a93c1718c8 Auto merge of #132116 - matthiaskrgr:rollup-3a0ia4r, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #131790 (Document textual format of SocketAddrV{4,6})
 - #131983 (Stabilize shorter-tail-lifetimes)
 - #132097 (sanitizer.md: LeakSanitizer is not supported on aarch64 macOS)
 - #132107 (Remove visit_expr_post from ast Visitor)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-24 20:28:20 +00:00
Matthias Krüger
91c025d741
Rollup merge of #131983 - dingxiangfei2009:stabilize-shorter-tail-lifetimes, r=lcnr
Stabilize shorter-tail-lifetimes

Close #131445
Tracked by #123739

We found a test case `tests/ui/drop/drop_order.rs` that had not been covered by the change. The test fixture is fixed now with the correct expectation.
2024-10-24 19:39:14 +02:00
bors
1d4a7670d4 Auto merge of #131985 - compiler-errors:const-pred, r=fee1-dead
Represent trait constness as a distinct predicate

cc `@rust-lang/project-const-traits`
r? `@ghost` for now

Also mirrored everything that is written below on this hackmd here: https://hackmd.io/`@compiler-errors/r12zoixg1l`

# Tl;dr:

* This PR removes the bulk of the old effect desugaring.
* This PR reimplements most of the effect desugaring as a new predicate and set of a couple queries. I believe it majorly simplifies the implementation and allows us to move forward more easily on its implementation.

I'm putting this up both as a request for comments and a vibe-check, but also as a legitimate implementation that I'd like to see land (though no rush of course on that last part).

## Background

### Early days

Once upon a time, we represented trait constness in the param-env and in `TraitPredicate`. This was very difficult to implement correctly; it had bugs and was also incomplete; I don't think this was anyone's fault though, it was just the limit of experimental knowledge we had at that point.

Dealing with `~const` within predicates themselves meant dealing with constness all throughout the trait solver. This was difficult to keep track of, and afaict was not handled well with all the corners of candidate assembly.

Specifically, we had to (in various places) remap constness according to the param-env constness:

574b64a97f/compiler/rustc_trait_selection/src/traits/select/mod.rs (L1498)

This was annoying and manual and also error prone.

### Beginning of the effects desugaring

Later on, #113210 reimplemented a new desugaring for const traits via a `<const HOST: bool>` predicate. This essentially "reified" the const checking and separated it from any of the remapping or separate tracking in param-envs. For example, if I was in a const-if-const environment, but I wanted to call a trait that was non-const, this reification would turn the constness mismatch into a simple *type* mismatch of the effect parameter.

While this was a monumental step towards straightening out const trait checking in the trait system, it had its own issues, since that meant that the constness of a trait (or any item within it, like an associated type) was *early-bound*. This essentially meant that `<T as Trait>::Assoc` was *distinct* from `<T as ~const Trait>::Assoc`, which was bad.

### Associated-type bound based effects desugaring

After this, #120639 implemented a new effects desugaring. This used an associated type to more clearly represent the fact that the constness is not an input parameter of a trait, but a property that could be computed of a impl. The write-up linked in that PR explains it better than I could.

However, I feel like it really reached the limits of what can comfortably be expressed in terms of associated type and trait calculus. Also, `<const HOST: bool>` remains a synthetic const parameter, which is observable in nested items like RPITs and closures, and comes with tons of its own hacks in the astconv and middle layer.

For example, there are pieces of unintuitive code that are needed to represent semantics like elaboration, and eventually will be needed to make error reporting intuitive, and hopefully in the future assist us in implementing built-in traits (eventually we'll want something like `~const Fn` trait bounds!).

elaboration hack: 8069f8d17a/compiler/rustc_type_ir/src/elaborate.rs (L133-L195)

trait bound remapping hack for diagnostics: 8069f8d17a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs (L2370-L2413)

I want to be clear that I don't think this is a issue of implementation quality or anything like that; I think it's simply a very clear sign that we're using types and traits in a way that they're not fundamentally supposed to be used, especially given that constness deserves to be represented as a first-class concept.

### What now?

This PR implements a new desugaring for const traits. Specifically, it introduces a `HostEffect` predicate to represent the obligation an impl is const, rather than using associated type bounds and the compat trait that exists for effects today.

### `HostEffect` predicate

A `HostEffect` clause has two parts -- the `TraitRef` we're trying to prove, and a `HostPolarity::{Maybe, Const}`.

`HostPolarity::Const` corresponds to `T: const Trait` bounds, which must *always* be proven as const, and which can be written in any context. These are lowered directly into the predicates of an item, since they're not "context-specific".

On the other hand, `HostPolarity::Maybe` corresponds to `T: ~const Trait` bounds which must only exist in a conditionally-const context like a method in a `#[const_trait]`, or a `const fn` free function. We do not lower these immediately into the predicates of an item; instead, we collect them into a new query called the **`const_conditions`**. These are the set of trait refs that we need to prove have const implementations for an item to be const.

Notably, they're represented as bare (poly) trait refs because they are meant to be paired back together with a `HostPolarity` when they're being registered in typeck (see next section).

For example, given:

```rust
const fn foo<T: ~const A + const B>() {}
```

`foo`'s const conditions would contain `T: A`, but not `T: B`. On the flip side, foo's predicates (`predicates_of`) query would contain `HostEffect(T: B, HostPolarity::Const)` but not `HostEffect(T: A, HostPolarity::Maybe)` since we don't need to prove that predicate in a non-const environment (and it's not even the right predicate to prove in an unconditionally const environment).

### Type checking const bodies

When type checking bodies in HIR, when we encounter a call expression, we additionally register the callee item's const conditions with the `HostPolarity` from the body we're typechecking (`Const` for unconditionally const things like `const`/`static` items, and `Maybe` for conditionally const things like const fns; and we don't register `HostPolarity` predicates for non-const bodies).

When type-checking a conditionally const body, we augment its param-env with `HostEffect(..., Maybe)` predicates.

### Checking that const impls are WF

We extend the logic in `compare_method_predicate_entailment` to also check the const-conditions of the impl method, to make sure that we error for:

```rust
#[const_trait] Bar {}
#[const_trait] trait Foo {
    fn method<T: Bar>();
}

impl Foo for () {
    fn method<T: ~const Bar>() {} // stronger assumption!
}
```

We also extend the WF check for impls to register the const conditions of the trait that is being implemented. This is to make sure we error for:

```rust
#[const_trait] trait Bar {}
#[const_trait] trait Foo<T> where T: ~const Bar {}

impl<T> const Foo<T> for () {}
//~^ `T: ~const Bar` is missing!
```

### Proving a `HostEffect` predicate

We have several ways of proving a `HostEffect` predicate:

1. Matching a `HostEffect` predicate from the param-env
2. From an impl - we do impl selection very similar to confirming a trait goal, except we filter for only const impls, and we additionally register the impl's const conditions (i.e. the impl's `~const` where clauses).

Later I expect that we will add more built-in implementations for things like `Fn`.

## What next?

After this PR, I'd like to split out the work more so it can proceed in parallel and probably amongst others that are not me.

* Register `HostEffect` goal for places in HIR typeck that correspond to call terminators, like autoderef.
* Make traits in libstd const again.
    * Probably need to impl host effect preds in old solver.
* Implement built-in `HostEffect` rules for traits like `Fn`.
* Rip out const checking from MIR altogether.

## So what?

This ends up being super convenient basically everywhere in the compiler. Due to the design of the new trait solver, we end up having an almost parallel structure to the existing trait and projection predicates for assembling `HostEffect` predicates; adding new candidates and especially new built-in implementations is now basically trivial, and it's quite straightforward to understand the confirmation logic for these predicates.

Same with diagnostics reporting; since we have predicates which represent the obligation to prove an impl is const, we can simplify and make these diagnostics richer without having to write a ton of logic to intercept and rewrite the existing `Compat` trait errors.

Finally, it gives us a much more straightforward path for supporting the const effect on the old trait solver. I'm personally quite passionate about getting const trait support into the hands of users without having to wait until the new solver lands[^1], so I think after this PR lands we can begin to gauge how difficult it would be to implement constness in the old trait solver too. This PR will not do this yet.

[^1]: Though this is not a prerequisite or by any means the only justification for this PR.
2024-10-24 17:33:42 +00:00
Michael Goulet
0f5a47d088 Be better at enforcing that const_conditions is only called on const items 2024-10-24 09:46:36 +00:00
Michael Goulet
25c9253379 Add tests 2024-10-24 09:46:36 +00:00
Michael Goulet
779b3943d3 Add next-solver to more effects tests 2024-10-24 09:46:36 +00:00
Michael Goulet
cde29b9ec9 Implement const effect predicate in new solver 2024-10-24 09:46:36 +00:00
Michael Goulet
a16d491054 Remove associated type based effects logic 2024-10-24 09:46:36 +00:00
Matthias Krüger
0470728e94
Rollup merge of #132084 - compiler-errors:param-env-with-err, r=lcnr,estebank
Consider param-env candidates even if they have errors

I added this logic in https://github.com/rust-lang/rust/pull/106309, but frankly I don't know why -- the logic was a very large hammer. It seems like recent changes to error tainting has made that no longer necessary.

Ideally we'd rework the way we handle error reporting in all of candidate assembly to be a bit more responsible; we're just suppressing candidates all willy-nilly and it leads to mysterious *other* errors cropping up, like the one that #132082 originally wanted to fix.

**N.B.** This has the side-effect of turning a failed resolution like `where Missing: Sized` into a trivial where clause that matches all types, but also I don't think it really matters?

I'm putting this up as an alternative to #132082, since that PR doesn't address the case when one desugars the APIT into a regular type param.

r? lcnr vibeck
2024-10-24 10:35:40 +02:00
Matthias Krüger
93bf791e8b
Rollup merge of #129248 - compiler-errors:raw-ref-deref, r=nnethercote
Taking a raw ref (`&raw (const|mut)`) of a deref of pointer (`*ptr`) is always safe

T-opsem decided in https://github.com/rust-lang/reference/pull/1387 that `*ptr` is only unsafe if the place is accessed. This means that taking a raw ref of a deref expr is always safe, since it doesn't constitute a read.

This also relaxes the `DEREF_NULLPTR` lint to stop warning in the case of raw ref of a deref'd nullptr, and updates its docs to reflect that change in the UB specification.

This does not change the behavior of `addr_of!((*ptr).field)`, since field projections still require the projection is in-bounds.

I'm on the fence whether this requires an FCP, since it's something that is guaranteed by the reference you could ostensibly call this a bugfix since we were counting truly safe operations as unsafe. Perhaps someone on opsem has a strong opinion? cc `@rust-lang/opsem`
2024-10-24 10:35:39 +02:00
Duncan Proctor
10b60eba9b add third help hint to diagnostic error E0027 2024-10-24 03:17:28 -04:00
Greg Echelberger
cc0ec046b1 Fix #131977 parens mangled in shared mut static lint suggestion 2024-10-24 03:34:37 +00:00
Stuart Cook
7e2bbc30b3
Rollup merge of #132088 - compiler-errors:extern-static, r=jieyouxu
Print safety correctly in extern static items

Fixes #132080

r? spastorino or anyone really
2024-10-24 14:19:58 +11:00
Stuart Cook
f7f411dd4e
Rollup merge of #131930 - clubby789:revision-cfg-collide, r=jieyouxu
Don't allow test revisions that conflict with built in cfgs

Fixes #128964

Sorry `@heysujal` I started working on this about 1 minute before your comment by complete coincidence 😅
2024-10-24 14:19:56 +11:00
Stuart Cook
4b02d642dd
Rollup merge of #131909 - clubby789:enum-overflow-cast, r=compiler-errors
Prevent overflowing enum cast from ICEing

Fixes #131902
2024-10-24 14:19:56 +11:00
Stuart Cook
4c0bab3192
Rollup merge of #131898 - lukas-code:ptr-cast-cleanup, r=compiler-errors
minor `*dyn` cast cleanup

Small follow-up to https://github.com/rust-lang/rust/pull/130234 to remove a redundant check and clean up comments. No functional changes.

Also, explain why casts cannot drop the principal even though coercions can, and add a test because apparently we didn't have one already.

r? `@WaffleLapkin` or `@compiler-errors`
2024-10-24 14:19:55 +11:00
Stuart Cook
ad43be310f
Rollup merge of #131756 - compiler-errors:deeply-normalize-type-err, r=lcnr
Deeply normalize `TypeTrace` when reporting type error in new solver

Normalize the values that come from the `TypeTrace` for various type mismatches.

Side-note: We can't normalize the `TypeError` itself bc it may come from instantiated binders, so it may reference values from within the probe...

r? lcnr
2024-10-24 14:19:55 +11:00
Stuart Cook
9c73bcfa8d
Rollup merge of #130225 - adetaylor:rename-old-receiver, r=wesleywiser
Rename Receiver -> LegacyReceiver

As part of the "arbitrary self types v2" project, we are going to replace the current `Receiver` trait with a new mechanism based on a new, different `Receiver` trait.

This PR renames the old trait to get it out the way. Naming is hard. Options considered included:
* HardCodedReceiver (because it should only be used for things in the standard library, and hence is sort-of hard coded)
* LegacyReceiver
* TargetLessReceiver
* OldReceiver

These are all bad names, but fortunately this will be temporary. Assuming the new mechanism proceeds to stabilization as intended, the legacy trait will be removed altogether.

Although we expect this trait to be used only in the standard library, we suspect it may be in use elsehwere, so we're landing this change separately to identify any surprising breakages.

It's known that this trait is used within the Rust for Linux project; a patch is in progress to remove their dependency.

This is a part of the arbitrary self types v2 project,
https://github.com/rust-lang/rfcs/pull/3519
https://github.com/rust-lang/rust/issues/44874

r? `@wesleywiser`
2024-10-24 14:19:53 +11:00
Michael Goulet
4217b8702d Deeply normalize type trace in type error reporting 2024-10-24 02:48:28 +00:00
Michael Goulet
d8dc31fd3d Consider param-env candidates even if they have errors 2024-10-24 01:48:44 +00:00
Michael Goulet
4e1b3ab0e7 Print safety correctly in extern static items 2024-10-24 00:41:27 +00:00
Ding Xiang Fei
6d569f769c
stabilize if_let_rescope 2024-10-24 04:33:14 +08:00
Ding Xiang Fei
fd36b3a4a8
s/SmartPointer/CoerceReferent/g
move derive_smart_pointer into removed set
2024-10-24 02:14:09 +08:00
clubby789
2e3091d66c Don't allow test revisions that conflict with built in cfgs 2024-10-23 18:05:27 +00:00
Ding Xiang Fei
0689b2139f
stabilize shorter-tail-lifetimes 2024-10-24 01:56:08 +08:00
Josh Triplett
ecdc2441b6 "innermost", "outermost", "leftmost", and "rightmost" don't need hyphens
These are all standard dictionary words and don't require hyphenation.
2024-10-23 02:45:24 -07:00
bors
9abfcb4900 Auto merge of #132053 - matthiaskrgr:rollup-u5ds6i3, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #131707 (Run most `core::num` tests in const context too)
 - #132002 (abi/compatibility: also test Option-like types)
 - #132026 (analyse: remove unused uncanonicalized field)
 - #132031 (Optimize `Rc<T>::default`)
 - #132040 (relnotes: fix stabilizations of `assume_init`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-23 05:57:00 +00:00
Matthias Krüger
7e1dbaec13
Rollup merge of #132002 - RalfJung:abi-compat-option-like, r=compiler-errors
abi/compatibility: also test Option-like types

Adds tests for the decision [here](https://github.com/rust-lang/rust/pull/130628#issuecomment-2402761599).

Cc ``@workingjubilee``
2024-10-23 06:51:24 +02:00
Michael Goulet
febb3f7c88 Represent TraitBoundModifiers as distinct parts in HIR 2024-10-22 19:48:44 +00:00
bors
86d69c705a Auto merge of #132035 - matthiaskrgr:rollup-ty1e4q0, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #125205 (Fixup Windows verbatim paths when used with the `include!` macro)
 - #131049 (Validate args are correct for `UnevaluatedConst`, `ExistentialTraitRef`/`ExistentialProjection`)
 - #131549 (Add a note for `?` on a `impl Future<Output = Result<..>>` in sync function)
 - #131731 (add `TestFloatParse` to `tools.rs` for bootstrap)
 - #131732 (Add doc(plugins), doc(passes), etc. to INVALID_DOC_ATTRIBUTES)
 - #132006 (don't stage-off to previous compiler when CI rustc is available)
 - #132022 (Move `cmp_in_dominator_order` out of graph dominator computation)
 - #132033 (compiletest: Make `line_directive` return a `DirectiveLine`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-22 14:16:37 +00:00
Matthias Krüger
457087ed29
Rollup merge of #131549 - compiler-errors:try-in-sync, r=spastorino
Add a note for `?` on a `impl Future<Output = Result<..>>` in sync function

It's confusing to `?` a future of a result in a sync function. We have a suggestion to `.await` it if we're in an async function, but not a sync function. Note that this is the case for sync functions, at least.

Let's be a bit more vague about a fix, since it's somewhat context dependent. For example, you could block on it, or you could make your function asynchronous. 🤷
2024-10-22 15:28:41 +02:00
Adrian Taylor
8f85b90ca6 Rename Receiver -> LegacyReceiver
As part of the "arbitrary self types v2" project, we are going to
replace the current `Receiver` trait with a new mechanism based on a
new, different `Receiver` trait.

This PR renames the old trait to get it out the way. Naming is hard.
Options considered included:
* HardCodedReceiver (because it should only be used for things in the
  standard library, and hence is sort-of hard coded)
* LegacyReceiver
* TargetLessReceiver
* OldReceiver

These are all bad names, but fortunately this will be temporary.
Assuming the new mechanism proceeds to stabilization as intended, the
legacy trait will be removed altogether.

Although we expect this trait to be used only in the standard library,
we suspect it may be in use elsehwere, so we're landing this change
separately to identify any surprising breakages.

It's known that this trait is used within the Rust for Linux project; a
patch is in progress to remove their dependency.

This is a part of the arbitrary self types v2 project,
https://github.com/rust-lang/rfcs/pull/3519
https://github.com/rust-lang/rust/issues/44874

r? @wesleywiser
2024-10-22 12:55:16 +00:00
bors
bca5fdebe0 Auto merge of #131321 - RalfJung:feature-activation, r=nnethercote
terminology: #[feature] *enables* a feature (instead of "declaring" or "activating" it)

Mostly, we currently call a feature that has a corresponding `#[feature(name)]` attribute in the current crate a "declared" feature. I think that is confusing as it does not align with what "declaring" usually means. Furthermore, we *also* refer to `#[stable]`/`#[unstable]` as *declaring* a feature (e.g. in [these diagnostics](f25e5abea2/compiler/rustc_passes/messages.ftl (L297-L301))), which aligns better with what "declaring" usually means. To make things worse, the functions  `tcx.features().active(...)` and  `tcx.features().declared(...)` both exist and they are doing almost the same thing (testing whether a corresponding `#[feature(name)]`  exists) except that `active` would ICE if the feature is not an unstable lang feature. On top of this, the callback when a feature is activated/declared is called `set_enabled`, and many comments also talk about "enabling" a feature.

So really, our terminology is just a mess.

I would suggest we use "declaring a feature" for saying that something is/was guarded by a feature (e.g. `#[stable]`/`#[unstable]`), and "enabling a feature" for  `#[feature(name)]`. This PR implements that.
2024-10-22 11:02:35 +00:00
Ralf Jung
46ce5cbf33 terminology: #[feature] *enables* a feature (instead of "declaring" or "activating" it) 2024-10-22 07:37:54 +01:00
bors
f225713007 Auto merge of #132020 - workingjubilee:rollup-a8iehqg, r=workingjubilee
Rollup of 6 pull requests

Successful merges:

 - #130432 (rust_for_linux: -Zregparm=<N> commandline flag for X86 (#116972))
 - #131697 (`rt::Argument`: elide lifetimes)
 - #131807 (Always specify `llvm_abiname` for RISC-V targets)
 - #131954 (shave 150ms off bootstrap)
 - #132015 (Move const trait tests from `ui/rfcs/rfc-2632-const-trait-impl` to `ui/traits/const-traits`)
 - #132017 (Update triagebot.toml)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-22 05:49:18 +00:00
Jubilee
1ea4eabb81
Rollup merge of #132015 - compiler-errors:move-const-trait-tests, r=fee1-dead
Move const trait tests from `ui/rfcs/rfc-2632-const-trait-impl` to `ui/traits/const-traits`

I found the old test directory to be somewhat long to name, and I don't think it's necessary to put an experimental implementation's tests under an rfc which is closed.

r? fee1-dead

Breaking this out of #131985 so that PR doesn't touch 300 files.
2024-10-21 20:32:02 -07:00
Jubilee
763fbf8a90
Rollup merge of #131697 - ShE3py:rt-arg-lifetimes, r=Amanieu
`rt::Argument`: elide lifetimes

`@rustbot` label +C-cleanup
2024-10-21 20:32:01 -07:00
Jubilee
fe2cbbd2d5
Rollup merge of #130432 - azhogin:azhogin/regparm, r=workingjubilee,pnkfelix
rust_for_linux: -Zregparm=<N> commandline flag for X86 (#116972)

Command line flag `-Zregparm=<N>` for X86 (32-bit) for rust-for-linux: https://github.com/rust-lang/rust/issues/116972
Implemented in the similar way as fastcall/vectorcall support (args are marked InReg if fit).
2024-10-21 20:32:00 -07:00
bors
1de57a5ce9 Auto merge of #129935 - RalfJung:unsupported_calling_conventions, r=compiler-errors
make unsupported_calling_conventions a hard error

This has been a future-compat lint (not shown in dependencies) since Rust 1.55, released 3 years ago. Hopefully that was enough time so this can be made a hard error now. Given that long timeframe, I think it's justified to skip the "show in dependencies" stage. There were [not many crates hitting this](https://github.com/rust-lang/rust/pull/86231#issuecomment-866300943) even when the lint was originally added.

This should get cratered, and I assume then it needs a t-compiler FCP. (t-compiler because this looks entirely like an implementation oversight -- for the vast majority of ABIs, we already have a hard error, but some were initially missed, and we are finally fixing that.)

Fixes https://github.com/rust-lang/rust/pull/87678
2024-10-22 03:24:40 +00:00
Michael Goulet
e91267f3f0 Move tests 2024-10-22 00:03:09 +00:00
Ralf Jung
d567fcc301 abi/compatibility: also test Option-like types 2024-10-21 18:24:45 +01:00
Matthias Krüger
780a8c32cc
Rollup merge of #132001 - lcnr:stabilize-coherence-again, r=compiler-errors
fix coherence error for very large tuples™

see https://rust-lang.zulipchat.com/#narrow/channel/364551-t-types.2Ftrait-system-refactor/topic/diesel.20error for an in-depth explanation of this issue. We once again specialize `NormalizesTo` goals to avoid the impact of erasing their expected term.

fixes #131969

r? `@compiler-errors`
2024-10-21 18:11:22 +02:00
Matthias Krüger
4aa07a7867
Rollup merge of #131999 - jieyouxu:unit-bindings, r=WaffleLapkin
Improve test coverage for `unit_bindings` lint

Follow-up to #112380, apparently at the time I didn't add much of any test coverage outside of just "generally works as intended on the test suites and in the crater run".

r? compiler
2024-10-21 18:11:22 +02:00
Matthias Krüger
a9da2be010
Rollup merge of #131991 - jannden:issue-98565-test, r=jieyouxu
test: Add test for trait in FQS cast, issue #98565

Closes #98565 by adding a test to check for diagnostics when the built-in type `str` is used in a cast where a trait is expected.
2024-10-21 18:11:21 +02:00
Matthias Krüger
20b1dadf92
Rollup merge of #130350 - RalfJung:strict-provenance, r=dtolnay
stabilize Strict Provenance and Exposed Provenance APIs

Given that [RFC 3559](https://rust-lang.github.io/rfcs/3559-rust-has-provenance.html) has been accepted, t-lang has approved the concept of provenance to exist in the language. So I think it's time that we stabilize the strict provenance and exposed provenance APIs, and discuss provenance explicitly in the docs:
```rust
// core::ptr
pub const fn without_provenance<T>(addr: usize) -> *const T;
pub const fn dangling<T>() -> *const T;
pub const fn without_provenance_mut<T>(addr: usize) -> *mut T;
pub const fn dangling_mut<T>() -> *mut T;
pub fn with_exposed_provenance<T>(addr: usize) -> *const T;
pub fn with_exposed_provenance_mut<T>(addr: usize) -> *mut T;

impl<T: ?Sized> *const T {
    pub fn addr(self) -> usize;
    pub fn expose_provenance(self) -> usize;
    pub fn with_addr(self, addr: usize) -> Self;
    pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self;
}

impl<T: ?Sized> *mut T {
    pub fn addr(self) -> usize;
    pub fn expose_provenance(self) -> usize;
    pub fn with_addr(self, addr: usize) -> Self;
    pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self;
}

impl<T: ?Sized> NonNull<T> {
    pub fn addr(self) -> NonZero<usize>;
    pub fn with_addr(self, addr: NonZero<usize>) -> Self;
    pub fn map_addr(self, f: impl FnOnce(NonZero<usize>) -> NonZero<usize>) -> Self;
}
```

I also did a pass over the docs to adjust them, because this is no longer an "experiment". The `ptr` docs now discuss the concept of provenance in general, and then they go into the two families of APIs for dealing with provenance: Strict Provenance and Exposed Provenance. I removed the discussion of how pointers also have an associated "address space" -- that is not actually tracked in the pointer value, it is tracked in the type, so IMO it just distracts from the core point of provenance. I also adjusted the docs for `with_exposed_provenance` to make it clear that we cannot guarantee much about this function, it's all best-effort.

There are two unstable lints associated with the strict_provenance feature gate; I moved them to a new [strict_provenance_lints](https://github.com/rust-lang/rust/issues/130351) feature since I didn't want this PR to have an even bigger FCP. ;)

`@rust-lang/opsem` Would be great to get some feedback on the docs here. :)
Nominating for `@rust-lang/libs-api.`

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

[FCP comment](https://github.com/rust-lang/rust/pull/130350#issuecomment-2395114536)
2024-10-21 18:11:19 +02:00
lcnr
919b61a6f4 don't bail when encountering many placeholders 2024-10-21 17:51:43 +02:00
lcnr
b64b25b99e normalizes-to disable infer var check 2024-10-21 16:25:42 +02:00
Ralf Jung
56ee492a6e move strict provenance lints to new feature gate, remove old feature gates 2024-10-21 15:22:17 +01:00
许杰友 Jieyou Xu (Joe)
70ce711098 unit_bindings: improve test coverage 2024-10-21 21:33:33 +08:00
Jan Cibulka
d5cfcc71e8
test: Add test for trait in FQS cast, issue #98565 2024-10-21 11:45:19 +03:00
bors
3e33bda032 Auto merge of #130628 - workingjubilee:clean-up-result-ffi-guarantees, r=RalfJung
Finish stabilization of `result_ffi_guarantees`

The internal linting has been changed, so all that is left is making sure we stabilize what we want to stabilize.
2024-10-21 08:38:45 +00:00
Jubilee Young
7baf06680c lang: Strengthen RFC 3391 guarantees to match T-lang consensus 2024-10-21 00:43:36 -07:00
bors
93742bd782 Auto merge of #131988 - matthiaskrgr:rollup-tx173wn, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #126588 (Added more scenarios where comma to be removed in the function arg)
 - #131728 (bootstrap: extract builder cargo to its own module)
 - #131968 (Rip out old effects var handling code from traits)
 - #131981 (Remove the `BoundConstness::NotConst` variant)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-21 06:13:34 +00:00
Matthias Krüger
9ff4dab396
Rollup merge of #126588 - linyihai:trim-extra-comma, r=petrochenkov
Added more scenarios where comma to be removed in the function arg

This is an attempt to address the problem methion in https://github.com/rust-lang/rust/issues/106304#issuecomment-1837273666.

Copy the annotation to explain the fix

If the next Error::Extra ("next") doesn't next to current ("current")

```
fn foo(_: (), _: u32) {}
- foo("current", (), 1u32, "next")
+ foo((), 1u32)
```

If the previous error is not a `Error::Extra`, then do not trim the next comma

```
- foo((), "current", 42u32, "next")
+ foo((), 42u32)
```

Frankly, this is a fix from a test case and may not cover all scenarios
2024-10-21 07:01:36 +02:00
bors
f2ba41113d Auto merge of #130950 - compiler-errors:yeet-eval, r=BoxyUwU
Continue to get rid of `ty::Const::{try_}eval*`

This PR mostly does:

* Removes all of the `try_eval_*` and `eval_*` helpers from `ty::Const`, and replace their usages with `try_to_*`.
* Remove `ty::Const::eval`.
* Rename `ty::Const::normalize` to `ty::Const::normalize_internal`. This function is still used in the normalization code itself.
* Fix some weirdness around the `TransmuteFrom` goal.

I'm happy to split it out further; for example, I could probably land the first part which removes the helpers, or the changes to codegen which are more obvious than the changes to tools.

r? BoxyUwU

Part of https://github.com/rust-lang/rust/issues/130704
2024-10-21 03:46:28 +00:00
bors
7ed1a51b25 Auto merge of #131980 - matthiaskrgr:rollup-iy5nw71, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #131814 (`optimize` attribute applied to things other than methods/functions/c…)
 - #131927 (Check for filecheck directives in files marked `skip-filecheck`)
 - #131967 (Remove `lower_mono_bounds`)
 - #131973 (fix(rustdoc-json-types): document rustc-hash feature)
 - #131976 (feat(rustdoc-json-types): mark simple enums as copy)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-20 21:40:21 +00:00
Matthias Krüger
2a9b6d9626
Rollup merge of #131814 - Borgerr:misapplied-optimize-attribute, r=jieyouxu
`optimize` attribute applied to things other than methods/functions/c…

…losures gives an error (#128488)

Duplicate of #128943, which I had accidentally closed when rebasing.

cc. `@jieyouxu` `@compiler-errors` `@nikomatsakis` `@traviscross` `@pnkfelix.`
2024-10-20 21:04:13 +02:00
bors
662180b34d Auto merge of #131949 - Noratrieb:fxhashup-thanks-alona, r=WaffleLapkin
Update rustc-hash to version 2 but again

it's like #129533 but not closed by bors and rebased

r? WaffleLapkin meow
2024-10-20 19:01:54 +00:00
Lukas Markeffsky
46cc5e9e96 elaborate why dropping principal in *dyn casts is non-trivial 2024-10-20 17:54:04 +02:00
Matthias Krüger
6d43de643e
Rollup merge of #131843 - workingjubilee:thaw-impossible-reprs, r=lukas-code
compiler: Error on layout of enums with invalid reprs

Surprising no one, the ICEs with the same message have the same root cause.

Invalid reprs can reach layout computation for various reasons. For instance, the compiler may want to use its layout computations to discern if a combination of layout-affecting attributes results in a valid type to begin with by e.g. computing its size. When the input is bad, return an error reflecting that the answer to the question is not a useful one.
2024-10-20 16:54:10 +02:00
Matthias Krüger
7b714d4735
Rollup merge of #121560 - Noratrieb:stop-lint-macro-nonsense, r=jieyouxu
Allow `#[deny]` inside `#[forbid]` as a no-op

Forbid cannot be overriden. When someome tries to do this anyways, it results in a hard error. That makes sense.

Except it doesn't, because macros. Macros may reasonably use `#[deny]` (or `#[warn]` for an allow-by-default lint) in their expansion to assert that their expanded code follows the lint. This is doesn't work when the output gets expanded into a `forbid()` context. This is pretty silly, since both the macros and the code agree on the lint!

By making it a warning instead, we remove the problem with the macro, which is now nothing as warnings are suppressed in macro expanded code, while still telling users that something is up.

fixes #121483
2024-10-20 16:54:08 +02:00
ash
080103f1ed misapplied optimize attribute throws a compilation error (#128488) 2024-10-20 08:34:15 -06:00
Ralf Jung
de3cbf3c56 make unsupported_calling_conventions a hard error 2024-10-20 15:22:21 +02:00
Lin Yihai
f1070825bb Added more scenarios where commas need to be removed 2024-10-20 17:14:53 +08:00
Jubilee Young
9f4c9155d4 compiler: Reject impossible reprs during enum layout 2024-10-20 02:12:58 -07:00
Jubilee Young
68d1fd9427 compiler: pre-move code for fixing enum layout ICEs 2024-10-20 02:09:22 -07:00
Noratrieb
0c8d81b4df Stop relying on hashmap iteration for unused macro rules arms 2024-10-20 00:12:52 -07:00
Noratrieb
3efd5926f6 Stop relying on hashmap iteration for hir stat printing
Just because the code says it's OK does not mean that it actually is OK.
Nodes with the same total size were not sorted, their order relied on
hashmap iteration.
2024-10-20 00:12:52 -07:00
Jubilee Young
fa18606b17 compiler: Fully stabilize result_ffi_guarantees 2024-10-19 13:01:30 -07:00
Matthias Krüger
efd940d24a
Rollup merge of #131925 - clubby789:redundant-revision-cfg, r=jieyouxu
Warn on redundant `--cfg` directive when revisions are used

r? ``@jieyouxu``

Fixes #131390
Not sure of the best way to test this
2024-10-19 22:00:59 +02:00
Matthias Krüger
559f8ce726
Rollup merge of #131795 - compiler-errors:expectation, r=Nadrieril
Stop inverting expectation in normalization errors

We have some funky special case logic to invert the expectation and actual type for normalization errors depending on their cause code. IMO most of the error messages get better, except for `try {}` blocks' type expectations. I think that these need to be special cased in some other way, rather than via this hack.

Fixes #131763
2024-10-19 22:00:57 +02:00
Matthias Krüger
bc22740882
Rollup merge of #131789 - compiler-errors:capture-more, r=fmease
Make sure that outer opaques capture inner opaques's lifetimes even with precise capturing syntax

When lowering an opaque, we must capture and duplicate all of the lifetimes in the opaque's bounds to correctly lower the opaque's bounds. We do this *even if* the lifetime is not captured according to the `+ use<>` precise capturing bound; in that case, we will later reject that captured lifetime. For example, Given an opaque like `impl Sized + 'a + use<>`, we will still duplicate `'a` but later error that it is not mentioned in the `use<>` bound.

The current heuristic was not properly handling cases like:

```
//@ edition: 2024
fn foo<'a>() -> impl Trait<Assoc = impl Trait2> + use<> {}
```

Which forces the outer `impl Trait` to capture `'a` since `impl Trait2` *implicitly* captures `'a` due to the new lifetime capture rules for edition 2024. We were only capturing lifetimes syntactically mentioned in the bounds. (Note that this still is an error; we just need to capture `'a` so it is handled later in the compiler correctly -- hence the ICE in #131769 where a late-bound lifetime was being referenced outside of its binder).

This PR reworks the way we collect lifetimes to capture and duplicate in AST lowering to fix this.

Fixes #131769
2024-10-19 22:00:57 +02:00
Matthias Krüger
268fa31596
Rollup merge of #127675 - chenyukang:yukang-fix-127562-addr, r=petrochenkov
Remove invalid help diagnostics for const pointer

Partially addresses #127562
2024-10-19 22:00:55 +02:00
Matthias Krüger
b2d132f10e
Rollup merge of #116863 - workingjubilee:non-exhaustive-is-not-ffi-unsafe, r=jieyouxu
warn less about non-exhaustive in ffi

Bindgen allows generating `#[non_exhaustive] #[repr(u32)]` enums. This results in nonintuitive nonlocal `improper_ctypes` warnings, even when the types are otherwise perfectly valid in C.

Adjust for actual tooling expectations by avoiding warning on simple enums with only unit variants.

Closes https://github.com/rust-lang/rust/issues/116831
2024-10-19 22:00:54 +02:00
Michael Goulet
9453d2cfeb Fix transmute goal 2024-10-19 18:07:35 +00:00
Michael Goulet
70746d078e Make sure that outer opaques capture inner opaques's lifetimes even with precise capturing syntax 2024-10-19 18:02:26 +00:00
Matthias Krüger
a394d4928b
Rollup merge of #131537 - hirschenberger:master, r=compiler-errors
Fix range misleading field access

Fixes #131471 by checking if the range-start is a literal.
2024-10-19 17:25:33 +02:00
clubby789
d82a21f9ad Warn on redundant --cfg directive when revisions are used 2024-10-19 12:40:12 +00:00
clubby789
ab4222ad97 Prevent overflowing enum cast from ICEing 2024-10-19 09:44:37 +00:00
许杰友 Jieyou Xu (Joe)
1af9d11583 Expand test coverage for deny-inside-forbid interactions 2024-10-18 18:18:41 +02:00
Noratrieb
e78d78868a Allow #[deny(..)] inside #[forbid(..)] as a no-op with a warning
Forbid cannot be overriden. When someome tries to do this anyways,
it results in a hard error. That makes sense.

Except it doesn't, because macros. Macros may reasonably use `#[deny]`
in their expansion to assert
that their expanded code follows the lint. This is doesn't work when the
output gets expanded into a `forbid()` context. This is pretty silly,
since both the macros and the code agree on the lint!

Therefore, we allow `#[deny(..)]`ing a lint that's already forbidden,
keeping the level at forbid.
2024-10-18 18:18:41 +02:00
Falco Hirschenberger
8f2273e518 Fix #131471, range misleading field access
Fixes #131471 by checking if the range-start is a literal.
2024-10-18 17:27:28 +02:00
许杰友 Jieyou Xu (Joe)
765e8c75b0
Rollup merge of #131864 - lrh2000:upcast_reorder, r=WaffleLapkin
Never emit `vptr` for empty/auto traits

Emiting `vptr`s for empty/auto traits is unnecessary (#114942) and causes unsoundness in `trait_upcasting` (#131813). This PR should ensure that we never emit vtables for such traits. See the linked issues for more details.

I'm not sure if I can add tests for the vtable layout. So this PR only adds tests for the soundness hole (i.e., the segmentation fault will disappear after this PR).

Fixes #114942
Fixes #131813

Cc #65991 (tracking issue for `trait_upcasting`)

r? `@WaffleLapkin`  (per https://github.com/rust-lang/rust/issues/131813#issuecomment-2419969745)
2024-10-18 14:52:25 +01:00
Matthias Krüger
13b398401f
Rollup merge of #131857 - WaffleLapkin:dyn-drop-principal-3, r=compiler-errors
Allow dropping dyn principal

Revival of #126660, which was a revival of #114679. Fixes #126313.

Allows dropping principal when coercing trait objects, e.g. `dyn Debug + Send` -> `dyn Send`.

cc `@compiler-errors` `@Jules-Bertholet`
r? `@lcnr`
2024-10-18 06:59:07 +02:00
Ruihan Li
781bff0499 Never emit vptr for empty/auto traits 2024-10-18 12:34:56 +08:00
Jules Bertholet
c4bce0b8b1 Add more tests 2024-10-18 00:33:50 +02:00
Matthias Krüger
372e8c11c2
Rollup merge of #131833 - c-ryan747:patch-1, r=Noratrieb
Add `must_use` to `CommandExt::exec`

[CommandExt::exec](https://fburl.com/0qhpo7nu) returns a `std::io::Error` in the case exec fails, but its not currently marked as `must_use` making it easy to accidentally ignore it.

This PR adds the `must_use` attributed here as i think it fits the definition in the guide of [When to add #[must_use]](https://std-dev-guide.rust-lang.org/policy/must-use.html#when-to-add-must_use)
2024-10-17 20:47:31 +02:00
Michael Goulet
e3800a1a04 Allow dropping dyn principal 2024-10-17 20:43:31 +02:00
Andrew Zhogin
b3ae64d24f rust_for_linux: -Zregparm=<N> commandline flag for X86 (#116972) 2024-10-18 00:29:31 +07:00
Callum Ryan
9b5b607fd8
Fix must_use lint for command exec tests 2024-10-17 06:33:35 -07:00
Matthias Krüger
21c57f5490
Rollup merge of #128391 - cafce25:issue-128390, r=lcnr
Change orphan hint from "only" to "any uncovered type inside..."

Fix #128390
2024-10-17 12:07:19 +02:00
bors
06d261daf6 Auto merge of #129582 - nbdd0121:unwind, r=nnethercote
Make destructors on `extern "C"` frames to be executed

This would make the example in #123231 print "Noisy Drop". I didn't mark this as fixing the issue because the behaviour is yet to be spec'ed.

Tracking:

- https://github.com/rust-lang/rust/issues/74990
2024-10-17 04:34:51 +00:00
bors
798fb83f7d Auto merge of #131797 - matthiaskrgr:rollup-lzpze2k, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #130989 (Don't check unsize goal in MIR validation when opaques remain)
 - #131657 (Rustfmt `for<'a> async` correctly)
 - #131691 (Delay ambiguous intra-doc link resolution after `Cache` has been populated)
 - #131730 (Refactor some `core::fmt` macros)
 - #131751 (Rename `can_coerce` to `may_coerce`, and then structurally resolve correctly in the probe)
 - #131753 (Unify `secondary_span` and `swap_secondary_and_primary` args in `note_type_err`)
 - #131776 (Emscripten: Xfail backtrace ui tests)
 - #131777 (Fix trivially_copy_pass_by_ref in stable_mir)
 - #131778 (Fix needless_lifetimes in stable_mir)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-16 20:50:53 +00:00
Matthias Krüger
c8ec8e6989
Rollup merge of #131776 - hoodmane:emscripten-xfail-backtrace-tests, r=jieyouxu
Emscripten: Xfail backtrace ui tests

It is possible to link libunwind and use the normal backtrace code, but it fails to symbolize stack traces. I investigated and could get the list of instruction pointers and symbol names, but I'm not sure how to use the dwarf info to map from instruction pointer to source location. In any case, fixing this is not a high priority.

See https://github.com/rust-lang/rust/issues/131738

r?jieyouxu
2024-10-16 20:15:55 +02:00