Commit Graph

13196 Commits

Author SHA1 Message Date
bors f9567d0f2b Auto merge of #128991 - Nadrieril:rustfix-unreachable-pattern, r=compiler-errors
Add a machine-applicable suggestion to "unreachable pattern"
2024-09-14 07:04:57 +00:00
DianQK 25d434b254
Update try_question_mark_nop.rs test 2024-09-14 13:30:36 +08:00
DianQK c16c22cc9c
Simplify the canonical clone method to copy
The optimized clone method ends up as the following MIR:

```
_2 = copy ((*_1).0: i32);
_3 = copy ((*_1).1: u64);
_4 = copy ((*_1).2: [i8; 3]);
_0 = Foo { a: move _2, b: move _3, c: move _4 };
```

We can transform this to:

```
_0 = copy (*_1);
```
2024-09-14 13:30:35 +08:00
Stuart Cook 04e744e77d
Rollup merge of #130199 - compiler-errors:by-move, r=cjgillot
Don't call closure_by_move_body_def_id on FnOnce async closures in MIR validation

Refactors the check in #129847 to not unncessarily call the `closure_by_move_body_def_id` query for async closures that don't *need* a by-move body.

Fixes #130167
2024-09-14 11:53:12 +10:00
Giang Dao b0db3a7bed (fix) conflicting negative impl marker and add tests 2024-09-14 09:25:06 +08:00
Nadrieril 1f69638400 Add a machine-applicable suggestion to "unreachable pattern" 2024-09-13 21:01:29 +02:00
Matthias Krüger 7d36bfa6c0
Rollup merge of #130301 - RalfJung:clashing_extern_declarations, r=compiler-errors
some fixes for clashing_extern_declarations lint

There were two issues with the clashing_extern_declarations lint:
- It would accept non-`repr(C)` structs as compatible with each other by comparing their fields in declaration order, but the fields could have different memory order (and with `-Zrandomize-layout`, this can really happen).
- It would accept two types as compatible if `compare_layouts` returns `true`, but that function actually just compared the *ABI*, not the fully layout -- and all sized structs with more than 2 fields have the same ABI (`Abi::Aggregate`), so this missed a *lot* of cases.

We don't currently have a clear spec for what we *want* to consider "clashing" and what is fine, so I otherwise kept the original logic. I hope to have a t-lang discussion about this at some point. But meanwhile, these changes seem like clear bugfixes.
2024-09-13 18:25:46 +02:00
Matthias Krüger 24da940631
Rollup merge of #129320 - jder:issue-128848, r=compiler-errors
Fix crash when labeling arguments for call_once and friends

When calling a method on Fn* traits explicitly, argument diagnostics should point at the called method (eg Fn::call_once), not the underlying callee.

This PR makes 3 main changes:

* It uses TupleArguments to detect if the user called a Fn* method directly (`my_fn.call_once(…)`) or implicitly (`my_fn(…)`). If it was explicit, argument diagnostics should point at the call_once method, not the underlying callable.
* The previous state was causing confusion between the two arguments lists (which could be different lengths), causing an out-of-bounds slice indexing in #128848. I added a length assert to capture the requirement in case this regresses or happens in another case.
* Unfortunately, this assert tripped when the required arguments information was not available (`self.get_hir_params_with_generics` was returning an empty Vec), so I've updated that to return None when that information is not available. (cc `@strottos` if you have any comments, since you added this function in #121595) Sorry this causes a bunch of indentation changes, recommend reviewing [ignoring whitespace](https://github.com/rust-lang/rust/pull/129320/files?w=1).)

This is my first rustc PR, so please call out if you'd like this split into more commits (or PRs), style nits, etc. I will add a few comments/questions inline. Thank you!

Fixes #128848
2024-09-13 18:25:44 +02:00
Jesse Rusak 57de75050a When calling a method on Fn* traits explicitly, argument diagnostics should
point at the called method (eg Fn::call_once), not the underlying callee.

Fixes 128848
2024-09-13 09:33:51 -04:00
bors 473ae00839 Auto merge of #130303 - Zalathar:rollup-8vsqdox, r=Zalathar
Rollup of 3 pull requests

Successful merges:

 - #130245 (make basic allocation functions track_caller in Miri for nicer backtraces)
 - #130261 (skip target sanity check when it's a `local-rebuild`)
 - #130287 (rustdoc: rename `issue-\d+.rs` tests to have meaningful names (part 9))

r? `@ghost`
`@rustbot` modify labels: rollup
2024-09-13 11:27:53 +00:00
Ralf Jung f362a59c3e some fixes for clashing_extern_declarations lint 2024-09-13 11:51:17 +02:00
Stuart Cook 1c23c8ba0c
Rollup merge of #130287 - notriddle:notriddle/issue-d, r=jieyouxu
rustdoc: rename `issue-\d+.rs` tests to have meaningful names (part 9)

Follow up

* https://github.com/rust-lang/rust/pull/116214
* https://github.com/rust-lang/rust/pull/116432
* https://github.com/rust-lang/rust/pull/116824
* https://github.com/rust-lang/rust/pull/118105
* https://github.com/rust-lang/rust/pull/119561
* https://github.com/rust-lang/rust/pull/123574
* https://github.com/rust-lang/rust/pull/125382
* https://github.com/rust-lang/rust/pull/127671

As always, it's easier to review the commits one at a time. Don't use the Files Changed tab. It's confusing.
2024-09-13 19:38:01 +10:00
bors 5e842953cc Auto merge of #130052 - khuey:clear-dilocation-after-const-emission, r=michaelwoerister
Don't leave debug locations for constants sitting on the builder indefinitely

Because constants are currently emitted *before* the prologue, leaving the debug location on the IRBuilder spills onto other instructions in the prologue and messes up both line numbers as well as the point LLVM chooses to be the prologue end.

Example LLVM IR (irrelevant IR elided):
Before:
```
define internal { i64, i64 } `@_ZN3tmp3Foo18var_return_opt_try17he02116165b0fc08cE(ptr` align 8 %self) !dbg !347 { start:
  %self.dbg.spill = alloca [8 x i8], align 8
  %_0 = alloca [16 x i8], align 8
  %residual.dbg.spill = alloca [0 x i8], align 1
    #dbg_declare(ptr %residual.dbg.spill, !353, !DIExpression(), !357)
  store ptr %self, ptr %self.dbg.spill, align 8, !dbg !357
    #dbg_declare(ptr %self.dbg.spill, !350, !DIExpression(), !358)
```
After:
```
define internal { i64, i64 } `@_ZN3tmp3Foo18var_return_opt_try17h00b17d08874ddd90E(ptr` align 8 %self) !dbg !347 { start:
  %self.dbg.spill = alloca [8 x i8], align 8
  %_0 = alloca [16 x i8], align 8
  %residual.dbg.spill = alloca [0 x i8], align 1
    #dbg_declare(ptr %residual.dbg.spill, !353, !DIExpression(), !357)
  store ptr %self, ptr %self.dbg.spill, align 8
    #dbg_declare(ptr %self.dbg.spill, !350, !DIExpression(), !358)
```
Note in particular how !357 from %residual.dbg.spill's dbg_declare no longer falls through onto the store to %self.dbg.spill. This fixes argument values at entry when the constant is a ZST (e.g. `<Option as Try>::Residual`). This fixes #130003 (but note that it does *not* fix issues with argument values and non-ZST constants, which emit their own stores that have debug info on them, like #128945).

r? `@michaelwoerister`
2024-09-13 08:57:41 +00:00
bors a5efa01895 Auto merge of #107251 - dingxiangfei2009:let-chain-rescope, r=jieyouxu
Rescope temp lifetime in if-let into IfElse with migration lint

Tracking issue #124085

This PR shortens the temporary lifetime to cover only the pattern matching and consequent branch of a `if let`.

At the expression location, means that the lifetime is shortened from previously the deepest enclosing block or statement in Edition 2021. This warrants an Edition change.

Coming with the Edition change, this patch also implements an edition lint to warn about the change and a safe rewrite suggestion to preserve the 2021 semantics in most cases.

Related to #103108.
Related crater runs: https://github.com/rust-lang/rust/pull/129466.
2024-09-13 03:47:30 +00:00
Veera 741005792e Implement a Method to Seal `DiagInner`'s Suggestions 2024-09-12 21:27:44 -04:00
bors d3a8524e80 Auto merge of #129137 - camelid:lazy-def-macro-const, r=BoxyUwU
Fix anon const def-creation when macros are involved

Fixes #128016.

Ever since #125915, some `ast::AnonConst`s turn into `hir::ConstArgKind::Path`s,
which don't have associated `DefId`s. To deal with the fact that we don't have
resolution information in `DefCollector`, we decided to implement a process
where if the anon const *appeared* to be trivial (i.e., `N` or `{ N }`), we
would avoid creating a def for it in `DefCollector`. If later, in AST lowering,
we realized it turned out to be a unit struct literal, or we were lowering it
to something that didn't use `hir::ConstArg`, we'd create its def there.

However, let's say we have a macro `m!()` that expands to a reference to a free
constant `FOO`. If we use `m!()` in the body of an anon const (e.g., `Foo<{ m!() }>`),
then in def collection, it appears to be a nontrivial anon const and we create
a def. But the macro expands to something that looks like a trivial const arg,
but is not, so in AST lowering we "fix" the mistake we assumed def collection
made and create a def for it. This causes a duplicate definition ICE.

The long-term fix for this is to delay the creation of defs for all expression-like
nodes until AST lowering (see #128844 for an incomplete attempt at this). This
would avoid issues like this one that are caused by hacky workarounds. However,
doing this uncovers a pre-existing bug with opaque types that is quite involved
to fix (see #129023).

In the meantime, this PR fixes the bug by delaying def creation for anon consts
whose bodies are macro invocations until after we expand the macro and know
what is inside it. This is accomplished by adding information to create the
anon const's def to the data in `Resolver.invocation_parents`.

r? `@BoxyUwU`
2024-09-13 01:10:51 +00:00
Michael Howell 48c7e444b1 rustdoc: re-bless stderrs after renaming the test case 2024-09-12 13:48:51 -07:00
Michael Howell 061cbae7c9 rustdoc: rename `issue-\d+.rs` tests to have meaningful names 2024-09-12 13:47:51 -07:00
Michael Howell 9454a89ef0 Add URL and crate_name to test cases 2024-09-12 13:38:24 -07:00
Michael Goulet 575c15a72e Use Autoderef::silence_errors more liberally throughout diagnostics code 2024-09-12 14:48:01 -04:00
Michael Goulet d8a646fe77 Do not report an excessive number of overflow errors for an ever-growing deref impl 2024-09-12 14:48:01 -04:00
Ding Xiang Fei b4b2b356d9
simplify the suggestion notes 2024-09-13 02:43:49 +08:00
Noah Lev e0bd01167e Re-enable `ConstArgKind::Path` lowering by default
...and remove the `const_arg_path` feature gate as a result. It was only
a stopgap measure to fix the regression that the new lowering introduced
(which should now be fixed by this PR).
2024-09-12 13:56:01 -04:00
Matthias Krüger ed1602e480
Rollup merge of #130276 - compiler-errors:nalgebra-hang, r=lcnr
Add test for nalgebra hang in coherence

r? lcnr
2024-09-12 19:03:43 +02:00
Matthias Krüger cb1d80d1e5
Rollup merge of #130273 - lcnr:overflow-no-constraints, r=compiler-errors
more eagerly discard constraints on overflow

We always discard the results of overflowing goals inside of the trait solver. We previously did so when instantiating the response in `evaluate_goal`. Canonicalizing results only to later discard them is also  inefficient 🤷

It's simpler and nicer to debug to eagerly discard constraints inside of the query itself.

r? ``@compiler-errors``
2024-09-12 19:03:43 +02:00
Matthias Krüger 4428d6f363
Rollup merge of #130101 - RalfJung:const-cleanup, r=fee1-dead
some const cleanup: remove unnecessary attributes, add const-hack indications

I learned that we use `FIXME(const-hack)` on top of the "const-hack" label. That seems much better since it marks the right place in the code and moves around with the code. So I went through the PRs with that label and added appropriate FIXMEs in the code. IMO this means we can then remove the label -- Cc ``@rust-lang/wg-const-eval.``

I also noticed some const stability attributes that don't do anything useful, and removed them.

r? ``@fee1-dead``
2024-09-12 19:03:41 +02:00
Michael Goulet d3ebd232a5 Add test for nalgebra hang in coherence 2024-09-12 09:55:25 -04:00
Michael Goulet 9d5d03b7de Don't call extern_crate when local crate name is the same as a dependency and we have a trait error 2024-09-12 09:07:44 -04:00
bors 394c4060d2 Auto merge of #130269 - Zalathar:rollup-coxzt2t, r=Zalathar
Rollup of 8 pull requests

Successful merges:

 - #125060 (Expand documentation of PathBuf, discussing lack of sanitization)
 - #129367 (Fix default/minimum deployment target for Aarch64 simulator targets)
 - #130156 (Add test for S_OBJNAME & update test for LF_BUILDINFO cl and cmd)
 - #130160 (Fix `slice::first_mut` docs)
 - #130235 (Simplify some nested `if` statements)
 - #130250 (Fix `clippy::useless_conversion`)
 - #130252 (Properly report error on `const gen fn`)
 - #130256 (Re-run coverage tests if `coverage-dump` was modified)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-09-12 12:56:55 +00:00
lcnr 675c99f4d5 more eagerly discard constraints on overflow 2024-09-12 14:32:44 +02:00
Stuart Cook a3d9d13d7a
Rollup merge of #130252 - compiler-errors:const-gen, r=chenyukang
Properly report error on `const gen fn`

Fixes #130232

Also removes some (what I thought were unused) functions, and fixes a bug in clippy where we considered `gen fn` to be the same as `fn` because it was only built to consider asyncness.
2024-09-12 20:37:18 +10:00
Stuart Cook c7162da850
Rollup merge of #130156 - nebulark:test_buildinfo, r=jieyouxu
Add test for S_OBJNAME & update test for LF_BUILDINFO cl and cmd

Update the unit test for checking cl and cmd in LF_BUILDINFO. With llvm-pdbutil we can now more specifically check if the string appears at the right location instead of just checking whether the string exists at all.
Context: https://github.com/rust-lang/rust/issues/96475
2024-09-12 20:37:15 +10:00
Stuart Cook 65a5cd467d
Rollup merge of #129367 - madsmtm:fix-apple-aarch64-deployment-targets, r=jieyouxu
Fix default/minimum deployment target for Aarch64 simulator targets

The minimum that `rustc` encoded did not match [the version in Clang](https://github.com/llvm/llvm-project/blob/llvmorg-18.1.8/llvm/lib/TargetParser/Triple.cpp#L1900-L1932), and that meant that that when linking, Clang ended up bumping the version. See https://github.com/rust-lang/rust/issues/129432 for more motivation behind this change.

Specifically, this PR sets the correct deployment target of the following targets:
- `aarch64-apple-ios-sim` from 10.0 to 14.0
- `aarch64-apple-tvos-sim` from 10.0 to 14.0
- `aarch64-apple-watchos-sim` from 5.0 to 7.0
- `aarch64-apple-ios-macabi` from 13.1 to 14.0

I have chosen not to document the `-sim` changes in the platform support docs, as it is fundamentally uninteresting; the normal targets (e.g. `aarch64-apple-ios`) still have the same deployment target, and that's what developers should actually target.

r? compiler

CC `@BlackHoleFox`
2024-09-12 20:37:15 +10:00
bors f753bc769b Auto merge of #130249 - compiler-errors:sad-new-solver-coherence, r=lcnr
Revert "Stabilize `-Znext-solver=coherence`"

This is a clean revert of #121848, prepared by running:

```
$ git revert 17b322fa69 -m1
```

Which effectively reverts:
* a138a92615, 69fdd1457d, d93e047c9f, 1a893ac648

see: https://rust-lang.zulipchat.com/#narrow/stream/364551-t-types.2Ftrait-system-refactor/topic/nalgebra.20hang

Closes #130056

r? lcnr
2024-09-12 10:17:32 +00:00
Tim Neumann cf006f375d
small_data_threshold.rs: Adapt to LLVM head changes 2024-09-12 09:53:59 +02:00
bors 7c7372b6a1 Auto merge of #129369 - madsmtm:apple-cc-linker-pass-target, r=jieyouxu
Pass deployment target when linking with CC on Apple targets

This PR effectively implements what's also being considered in the `cc` crate [here](https://github.com/rust-lang/cc-rs/issues/1030#issuecomment-2051020649), that is:
- When linking macOS targets with CC, pass the `-mmacosx-version-min=.` option to specify the desired deployment target. Also, no longer pass `-m32`/`-m64`, these are redundant since we already pass `-arch`.
- When linking with CC on iOS, tvOS, watchOS and visionOS, only pass `-target` (we assume for these targets that CC forwards to Clang).

This is required to get the linker to emit the correct `LC_BUILD_VERSION` of the final binary. See https://github.com/rust-lang/rust/issues/129432 for more motivation behind this change.

r? compiler

CC `@BlackHoleFox`
2024-09-12 06:57:38 +00:00
Ralf Jung b72b42d36f move a test to a better location 2024-09-12 08:08:38 +02:00
Ralf Jung 7f7c73bd9c simplify float::classify logic 2024-09-12 08:08:38 +02:00
bors 1f51450c68 Auto merge of #117465 - paulmenage:small-data-limit, r=compiler-errors
Add -Z small-data-threshold

This flag allows specifying the threshold size above which LLVM should not consider placing small objects in a `.sdata` or `.sbss` section.

Support is indicated in the target options via the
small-data-threshold-support target option, which can indicate either an
LLVM argument or an LLVM module flag.  To avoid duplicate specifications
in a large number of targets, the default value for support is
DefaultForArch, which is translated to a concrete value according to the
target's architecture.
2024-09-12 04:27:08 +00:00
Jubilee 312b597a7e
Rollup merge of #129835 - RalfJung:float-tests, r=workingjubilee
enable const-float-classify test, and test_next_up/down on 32bit x86

The  test_next_up/down tests have been disabled on all 32bit x86 targets, which goes too far -- they should definitely work on our (tier 1) i686 target, it is only without SSE that we might run into trouble due to https://github.com/rust-lang/rust/issues/114479. However, I cannot reproduce that trouble any more -- maybe that got fixed by https://github.com/rust-lang/rust/pull/123351?

The  const-float-classify test relied on const traits "because we can", and got disabled when const traits got removed. That's an unfortunate reduction in test coverage of our float functionality, so let's restore the test in a way that does not rely on const traits.

The const-float tests are actually testing runtime behavior as well, and I don't think that runtime behavior is covered anywhere else. Probably they shouldn't be called "const-float", but we don't have a `tests/ui/float` folder... should I create one and move them there? Are there any other ui tests that should be moved there?

I also removed some FIXME referring to not use x87 for Rust-to-Rust-calls -- that has happened in #123351 so this got fixed indeed. Does that mean we can simplify all that float code again? I am not sure how to test it. Is running the test suite with an i586 target enough?

Cc ```@tgross35``` ```@workingjubilee```
2024-09-11 15:53:21 -07:00
Jubilee 6879ee6818
Rollup merge of #129103 - Nadrieril:dont-warn-empty-unreachable, r=compiler-errors
Don't warn empty branches unreachable for now

The [stabilization](https://github.com/rust-lang/rust/pull/122792) of `min_exhaustive_patterns` updated the `unreachable_pattern` lint to trigger on empty arms too. This has caused some amount of churn, and imposes an unjoyful `#[allow(unreachable_patterns)]` onto library authors who want to stay backwards-compatible.

While I think the lint should eventually cover these cases, for transition's sake I'd prefer to revert linting to what it was prior to stabilization, at least for now.

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

r? ``@compiler-errors``
2024-09-11 15:53:20 -07:00
Michael Goulet 594de02cba Properly deny const gen/async gen fns 2024-09-11 18:39:06 -04:00
Michael Goulet e866f8a97d Revert 'Stabilize -Znext-solver=coherence' 2024-09-11 17:57:04 -04:00
Matthias Krüger 66727ea1a2
Rollup merge of #130219 - ogoffart:missing-docs-test, r=Urgau
Fix false positive with `missing_docs` and `#[test]`

Since #130025, the compiler don't ignore missing_docs when compiling the tests. But there is now a false positive warning for every `#[test]`

For example, this code
```rust
//! Crate docs

fn just_a_test() {}
```

Would emit this warning when running `cargo test`

```
warning: missing documentation for a constant
 --> src/lib.rs:5:1
  |
4 | #[test]
  | ------- in this procedural macro expansion
5 | fn just_a_test() {}
  | ^^^^^^^^^^^^^^^^^^^
```
2024-09-11 20:04:25 +02:00
Matthias Krüger 5107ff4322
Rollup merge of #130123 - FedericoBruzzone:master, r=compiler-errors
Report the `note` when specified in `diagnostic::on_unimplemented`

Before this PR the `note` field was completely ignored for some reason, now it is shown (I think) correctly during the hir typechecking phase.

1. Report the `note` when specified in `diagnostic::on_unimplemented`
2. Added a test for unimplemented trait diagnostic
3. Added a test for custom unimplemented trait diagnostic

Close #130084

P.S. This is my first PR to rustc.
2024-09-11 20:04:23 +02:00
Matthias Krüger 1d6edee3fc
Rollup merge of #129520 - tunawasabi:suggest-adding-struct-pattern-syntax, r=compiler-errors
Suggest the correct pattern syntax on usage of unit variant pattern for a struct variant

Closes #126243

I add a suggestion on usage of unit variant pattern for a struct variant.
2024-09-11 20:04:22 +02:00
Matthias Krüger 76e070fbd3
Rollup merge of #129260 - wafarm:dont-suggest-closures, r=compiler-errors
Don't suggest adding return type for closures with default return type

Follow up of #129223

r? ``@compiler-errors``
2024-09-11 20:04:21 +02:00
Nadrieril 5b7be148ea Revert warning empty patterns as unreachable 2024-09-11 18:36:45 +02:00
bors f7f8bdf2e0 Auto merge of #130195 - folkertdev:naked-asm-outside-naked-fn, r=Amanieu
disallow `naked_asm!` outside of `#[naked]` functions

tracking issue: https://github.com/rust-lang/rust/issues/90957
parent PR: https://github.com/rust-lang/rust/pull/128651

I split this out from the parent PR because it's self-contained and because the analysis has to search through all functions and there might be performance regressions.

r? `@Amanieu`
2024-09-11 13:47:26 +00:00
Olivier Goffart cc34d64c51 Use `doc(hidden)` instead of `allow(missing_docs)` in the test harness
So that it doesn't fail with `forbid(missing_docs)`

Fixes #130218
2024-09-11 12:14:35 +02:00
Olivier Goffart 5d456dfaa1 Use `#[doc(hidden)]` instead of `#[allow(missing_docs)]` on the const generated for `#[test]` 2024-09-11 11:49:27 +02:00
Olivier Goffart 6eddbb704e Fix false positive with `missing_docs` and `#[test]`
Since #130025, the compiler don't ignore missing_docs when compiling the tests.
But there is now a false positive warning for every `#[test]`

For example, this code
```rust
//! Crate docs

fn just_a_test() {}
```

Would emit this warning when running `cargo test`

```
warning: missing documentation for a constant
 --> src/lib.rs:5:1
  |
4 | #[test]
  | ------- in this procedural macro expansion
5 | fn just_a_test() {}
  | ^^^^^^^^^^^^^^^^^^^
```
2024-09-11 11:33:10 +02:00
bors 5a2dd7d4f3 Auto merge of #130194 - lcnr:generalize-cache, r=compiler-errors
generalize: track relevant info in cache key

This was previously theoretically incomplete as we could incorrectly generalize as if the type was in an invariant context even though we're in a covariant one. Similar with the `in_alias` flag.

r? `@compiler-errors`
2024-09-11 07:17:12 +00:00
bors 4c5fc2c334 Auto merge of #130050 - cjgillot:expect-attr-id, r=fee1-dead
Enumerate lint expectations using AttrId

This PR implements the idea I outlined in https://github.com/rust-lang/rust/issues/127884#issuecomment-2240338547

We can uniquely identify a lint expectation `#[expect(lint0, lint1...)]` using the `AttrId` and the index of the lint inside the attribute. This PR uses this property in `check_expectations`.

In addition, this PR stops stashing expected diagnostics to wait for the unstable -> stable `LintExpectationId` mapping: if the lint is emitted with an unstable attribute, it must have been emitted by an `eval_always` query (like inside the resolver), so won't be loaded from cache. Decoding an `AttrId` from the on-disk cache ICEs, so we have no risk of accidentally checking an expectation.

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

cc `@xFrednet`
2024-09-11 04:49:56 +00:00
Ralf Jung e556c136f3 clean up internal comments about float semantics
- remove an outdated FIXME
- add reference to floating-point semantics issue

Co-authored-by: Jubilee <workingjubilee@gmail.com>
2024-09-10 16:47:09 -07:00
Ralf Jung 3daa9518d5 enable and extend float-classify test 2024-09-10 16:47:01 -07:00
Jubilee Young c40ee79b84 move float tests into their own dir 2024-09-10 16:05:37 -07:00
bors 6f7229c4da Auto merge of #129403 - scottmcm:only-array-simd, r=compiler-errors
Ban non-array SIMD

Nearing the end of https://github.com/rust-lang/compiler-team/issues/621 !

Currently blocked on ~~https://github.com/rust-lang/compiler-builtins/pull/673~~ ~~https://github.com/rust-lang/compiler-builtins/pull/674~~ ~~https://github.com/rust-lang/rust/pull/129400~~ ~~https://github.com/rust-lang/rust/pull/129481~~ for windows.
2024-09-10 22:47:40 +00:00
FedericoBruzzone 4cecf42971 Report the `note` when specified in `diagnostic::on_unimplemented`
Signed-off-by: FedericoBruzzone <federico.bruzzone.i@gmail.com>
2024-09-10 23:05:36 +02:00
bors 0ee7cb5e36 Auto merge of #130200 - matthiaskrgr:rollup-2g4ijc5, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #130143 (miri-test-libstd: add missing BOOTSTRAP_ARGS)
 - #130173 (rustdoc: add two regression tests)
 - #130175 (`rustc_mir_transform` cleanups 3)
 - #130184 (coverage: Clean up terminology in counter creation)
 - #130185 (abi/compatibility test: remove tests inside repr(C) wrappers)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-09-10 20:18:27 +00:00
Ding Xiang Fei 89682a5313
downgrade borrowck suggestion level due to possible span conflict 2024-09-11 04:10:04 +08:00
Ding Xiang Fei e2120a7c38
coalesce lint suggestions that can intersect 2024-09-11 04:10:03 +08:00
Ding Xiang Fei f93df1f7dc
rescope temp lifetime in let-chain into IfElse
apply rules by span edition
2024-09-11 04:10:00 +08:00
Paul Menage 3810386bbe Add -Z small-data-threshold
This flag allows specifying the threshold size above which LLVM should
not consider placing small objects in a .sdata or .sbss section.

Support is indicated in the target options via the
small-data-threshold-support target option, which can indicate either an
LLVM argument or an LLVM module flag.  To avoid duplicate specifications
in a large number of targets, the default value for support is
DefaultForArch, which is translated to a concrete value according to the
target's architecture.
2024-09-10 12:19:16 -07:00
Matthias Krüger a42d67e6cc
Rollup merge of #130185 - RalfJung:abi-compat-repr-c-wrappers, r=compiler-errors
abi/compatibility test: remove tests inside repr(C) wrappers

When I wrote the test I assumed we'd guarantee ABI compatibility to be "structural" wrt `repr(C)` types, i.e. if two `repr(C)` types have all their fields be pairwise ABI-compatible then the types are ABI-compatible. That got removed from the ABI compatibility docs before they landed, though, so let's also remove it from this test.
2024-09-10 17:35:16 +02:00
Matthias Krüger a204f87de8
Rollup merge of #130173 - fmease:rustdoc-regression-tests, r=notriddle
rustdoc: add two regression tests

They were basically copy/pasted from `tests/ui/` to `tests/rustdoc-ui/`.
Not sure if it's worth adding these, I can just close these issues as is if you want.

This brings the number of https://github.com/rust-lang/rust/labels/T-rustdoc + https://github.com/rust-lang/rust/labels/E-needs-test from 3 down to 1.
The remaining one – #103004 — is a nasty one to retroactively find a proper(!) test for.

Fixes #98250.
Fixes #107872.

r? rustdoc
2024-09-10 17:35:14 +02:00
Florian Schmiderer 713828d4f4 Add test for S_OBJNAME and update test for LF_BUILDINFO cl and cmd for
pdb files.
2024-09-10 17:23:05 +02:00
Michael Goulet 5cf117ed05 Don't call closure_by_move_body_def_id on FnOnce async closures in MIR validation 2024-09-10 10:55:05 -04:00
bors 33855f80d4 Auto merge of #130025 - Urgau:missing_docs-expect, r=petrochenkov
Also emit `missing_docs` lint with `--test` to fulfil expectations

This PR removes the "test harness" suppression of the `missing_docs` lint to be able to fulfil `#[expect]` (expectations) as it is now "relevant".

I think the goal was to maybe avoid false-positive while linting on public items under `#[cfg(test)]` but with effective visibility we should no longer have any false-positive.

Another possibility would be to query the lint level and only emit the lint if it's of expect level, but that is even more hacky.

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

try-job: x86_64-gnu-aux
2024-09-10 14:54:09 +00:00
lcnr 7a57a74bf5 generalize: track relevant info in cache key 2024-09-10 15:21:57 +02:00
Folkert de Vries 6ca5ec7b4e disallow `naked_asm!` outside of `#[naked]` functions 2024-09-10 15:19:14 +02:00
Ralf Jung 86075759cc abi/compatibility test: remove tests inside repr(C) wrappers 2024-09-10 13:18:20 +02:00
bors f827364a95 Auto merge of #129337 - EtomicBomb:rfc, r=notriddle
rustdoc rfc#3662 changes under unstable flags

* All new functionality is under unstable options
* Adds `--merge=shared|none|finalize` flags
* Adds `--parts-out-dir=<crate specific directory>` for `--merge=none`
to write cross-crate info file for a single crate
* Adds `--include-parts-dir=<previously specified directory>` for
`--merge=finalize` to write cross-crate info files
* `tests/rustdoc/` tests for the new flags
2024-09-10 11:15:51 +00:00
Ralf Jung 123757ae07 turn errors that should be impossible due to our static checks into ICEs 2024-09-10 10:27:30 +02:00
Ralf Jung f76f128dc9 const-eval interning: accpt interior mutable pointers in final value (but keep rejecting mutable references) 2024-09-10 10:26:16 +02:00
Zalathar e96b4e479a coverage: Extract `executor::block_on` from several async coverage tests
By moving `block_on` to an auxiliary crate, we avoid having to keep a separate
copy of it in every async test.

(This also incorporates some small tweaks to the headers in `await_ready.rs`.)
2024-09-10 16:08:36 +10:00
Scott McMurray d2309c2a9d Ban non-array SIMD 2024-09-09 19:39:43 -07:00
Jubilee a26c809e7a
Rollup merge of #130152 - krasimirgg:nsan, r=nikic
adapt a test for llvm 20

No functional changes intended.

``@rustbot`` label: +llvm-main
r? ``@nikic``
2024-09-09 19:20:38 -07:00
Jubilee 57273d82a8
Rollup merge of #130146 - folkertdev:bootstrap-naked-asm, r=Amanieu
bootstrap `naked_asm!` for `compiler-builtins`

tracking issue: https://github.com/rust-lang/rust/issues/90957
parent PR: https://github.com/rust-lang/rust/pull/128651

in this PR, `naked_asm!` is added as an alias for `asm!` with one difference: `options(noreturn)` is always enabled by `naked_asm!`. That makes it future-compatible for when `naked_asm!` starts disallowing `options(noreturn)` later.

The `naked_asm!` macro must be introduced first so that we can upgrade `compiler-builtins` to use it, and can then change the implementation of `naked_asm!` in https://github.com/rust-lang/rust/pull/128651

I've added some usages for `naked_asm!` in the tests, so we can be confident that it works, but I've left upgrading the whole test suite to the parent PR.

r? ``@Amanieu``
2024-09-09 19:20:38 -07:00
Jubilee 2859c24e64
Rollup merge of #130094 - workingjubilee:concurrency-is-real, r=lcnr
Inform the solver if evaluation is concurrent

Parallel compilation of a program can cause unexpected event sequencing. Inform the solver when this is true so it can skip invalid asserts.
2024-09-09 19:20:37 -07:00
Jubilee a4c61048d8
Rollup merge of #129529 - lqd:stable-new-solver, r=Kobzol
Add test to build crates used by r-a on stable

r? ````````@Kobzol````````

I've opened other PRs for this one to work and they've landed already. I cherry-picked your commit, and added the last remaining pieces we needed I think.
2024-09-09 19:20:36 -07:00
León Orell Valerian Liehr 6d61dfd2e4
rustdoc: add two regression tests 2024-09-09 22:35:10 +02:00
Jubilee Young d243c8fbc4 compiler: Inform the solver of concurrency
Parallel compilation of a program can cause unexpected event sequencing.
Inform the solver when this is true so it can skip invalid asserts, then
assert replaced solutions are equal if Some
2024-09-09 13:07:48 -07:00
Matthias Krüger 3b0221bf63
Rollup merge of #130137 - gurry:master, r=cjgillot
Fix ICE caused by missing span in a region error

Fixes #130012

The ICE occurs on line 634 in this error handling code: 085744b7ad/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs (L617-L637) It is caused by the span being a dummy span and `!span.is_dummy()` on line 628 evaluating to `false`.

A dummy span, however, is expected here thanks to the `Self: Trait` predicate from `predicates_of` (see line 61): 085744b7ad/compiler/rustc_hir_analysis/src/collect/predicates_of.rs (L61-L69)

This PR changes the error handling code to omit the note which needed the span instead of ICE'ing in the presence of a dummy span.
2024-09-09 20:20:20 +02:00
Matthias Krüger 1490fe6d16
Rollup merge of #130064 - folkertdev:fix-issue-129983, r=compiler-errors
fix ICE in CMSE type validation

fixes #129983

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

r? ``@compiler-errors``
2024-09-09 20:20:18 +02:00
Krasimir Georgiev 383f506227 adapt a test for llvm 20
No functional changes intended.
2024-09-09 13:29:47 +00:00
Urgau 0f9cb070bc Add test about missing docs at crate level 2024-09-09 14:51:39 +02:00
Urgau a1a8627dd7 Allow `missing_docs` lint on the generated test harness 2024-09-09 14:51:39 +02:00
Mads Marquart dd35398545 Pass deployment target when linking with cc on Apple targets
When linking macOS targets with cc, pass the `-mmacosx-version-min=.`
option to specify the desired deployment target. Also, no longer pass
`-m32`/`-m64`, these are redundant since we already pass `-arch`.

When linking with cc on other Apple targets, always pass `-target`.
(We assume for these targets that cc => clang).
2024-09-09 13:57:17 +02:00
Mads Marquart 97df8fb7ec Fix default/minimum deployment target for Aarch64 simulator targets
The minimum that `rustc` encoded did not match the version in Clang, and
that meant that that when linking, we ended up bumping the version.

Specifically, this sets the correct deployment target of the following
simulator and Mac Catalyst targets:
- `aarch64-apple-ios-sim` from 10.0 to 14.0
- `aarch64-apple-tvos-sim` from 10.0 to 14.0
- `aarch64-apple-watchos-sim` from 5.0 to 7.0
- `aarch64-apple-ios-macabi` from 13.1 to 14.0

I have chosen to not document the simulator target versions in the
platform support docs, as it is fundamentally uninteresting; the normal
targets (e.g. `aarch64-apple-ios`, `aarch64-apple-tvos`) still have the
same deployment target as before, and that's what developers should
actually target.
2024-09-09 13:55:14 +02:00
Folkert de Vries 02378997ea bootstrap `naked_asm!` for `compiler-builtins`
in this commit, `naked_asm!` is an alias for `asm!` with one difference: `options(noreturn)` is always enabled by `naked_asm!`. That makes it future-compatible for when `naked_asm!` starts disallowing `options(noreturn)` later.
2024-09-09 12:47:40 +02:00
Jubilee fad44c424f
Rollup merge of #130107 - RalfJung:const-ptr-is-null, r=oli-obk
const: make ptr.is_null() stop execution on ambiguity

This seems better than saying `false` -- saying `false` is in fact actively unsound if `NonNull` then uses this to permit putting this pointer inside of it, but at runtime it turns out to be null.

Part of https://github.com/rust-lang/rust/issues/74939
Cc ```@rust-lang/wg-const-eval```
2024-09-09 00:17:51 -07:00
Jubilee fd938c7441
Rollup merge of #130068 - madsmtm:deployment-target-test, r=jieyouxu
Test codegen when setting deployment target

Test our codegen in different scenarios when setting the deployment target. There are many places here where this is still incorrect, these will be fixed in https://github.com/rust-lang/rust/pull/129342, https://github.com/rust-lang/rust/pull/129367 and https://github.com/rust-lang/rust/pull/129369. See https://github.com/rust-lang/rust/issues/129432 for the bigger picture.

Tested locally using:
```console
./x test tests/run-make/apple-deployment-target --target="aarch64-apple-darwin,aarch64-apple-ios,aarch64-apple-ios-macabi,aarch64-apple-ios-sim,aarch64-apple-tvos,aarch64-apple-tvos-sim,aarch64-apple-visionos,aarch64-apple-visionos-sim,aarch64-apple-watchos,aarch64-apple-watchos-sim,arm64_32-apple-watchos,armv7s-apple-ios,i386-apple-ios,x86_64-apple-darwin,x86_64-apple-ios,x86_64-apple-ios-macabi,x86_64-apple-tvos,x86_64-apple-watchos-sim,x86_64h-apple-darwin"
```

The only Apple targets that aren't tested by the above command are:
- `arm64e-apple-darwin`, failed to build, see https://github.com/rust-lang/cc-rs/issues/1205.
- `armv7k-apple-watchos`, failed to link, see https://github.com/rust-lang/rust/issues/130071.
- `arm64e-apple-ios`, failed to link, see https://github.com/rust-lang/rust/issues/130085.
- `i686-apple-darwin`, requires a bit of setup and an older machine, see [the docs](https://doc.rust-lang.org/nightly/rustc/platform-support/i686-apple-darwin.html).
- `i386-apple-ios` requires you to set `IPHONEOS_DEPLOYMENT_TARGET=10.0` for the test helpers to work, will be fixed by https://github.com/rust-lang/cc-rs/issues/1030.

But all of this is as it was before this PR.

Fixes https://github.com/rust-lang/rust/issues/47825, since we now have a test that compiles a `dylib` for `aarch64-apple-ios`.

Split out from https://github.com/rust-lang/rust/pull/129342, see that for a little bit of the review that this has gone through already.

r? petrochenkov

```@rustbot``` label O-apple
2024-09-09 00:17:49 -07:00
Jubilee 4cfb1c3154
Rollup merge of #128667 - its-the-shrimp:rustdoc_json_types_rename, r=aDotInTheVoid
rustdoc: normalise type/field names

Updates #100961

- `Import` -> `Use`, to better reflect the terminology of Rust & its syntax
- `TypeBinding` -> `AssocItemConstraint`, to sync up with `clean`
- `FnDecl` -> `FunctionSignature`, because that's what it is
- `Header` -> `FunctionHeader`, because `Header` is a very word that's very heavily loaded with different meanings
- `ItemEnum::AssocType`: `default` -> `type`, because those items appear in `impl` blocks as well, where they're _not_ the "default"
- `ItemEnum::AssocConst`: `default` -> `value`, see the previous point
- `ForeignType` -> `ExternType`, because "foreign" is not the right word there
- boolean fields' names made to consistently be a phrase that can be a yes/no answer, e.g. `async` -> `is_async`

The docs of `ItemEnum::AssocType::type_` & of `ItemEnum::AssocConst::value` are also updated to be up to date with the clarification of the name of the fields
2024-09-09 00:17:47 -07:00
Jubilee 2cce01ee62
Rollup merge of #128345 - sthibaul:hurd-amd64, r=Urgau
added support for GNU/Hurd on x86_64
2024-09-09 00:17:46 -07:00
Jubilee 1ea466bdce
Rollup merge of #119229 - mati865:update-mingw-toolchain, r=jieyouxu,petrochenkov
Update mingw-w64 + GNU toolchain

The list of packaged tools and their versions is available at: https://github.com/niXman/mingw-builds-binaries/releases/tag/14.1.0-rt_v12-rev0

Fixes: https://github.com/rust-lang/rust/issues/112368
2024-09-09 00:17:46 -07:00
Gurinder Singh 0f8efb3b5c Fix ICE caused by missing span in a region error 2024-09-09 12:27:36 +05:30
Samuel Thibault 7626015848 added support for GNU/Hurd on x86_64 2024-09-08 23:37:07 +02:00
Ralf Jung 7a3a317618 remove const_slice_index annotations, it never had a feature gate anyway 2024-09-08 23:08:43 +02:00
Ralf Jung 11d51aae86 const: make ptr.is_null() stop execution on ambiguity 2024-09-08 19:07:46 +02:00
bors 6d05f12170 Auto merge of #129346 - nnethercote:fix-double-handling-in-collect_tokens, r=petrochenkov
Fix double handling in `collect_tokens`

Double handling of AST nodes can occur in `collect_tokens`. This is when an inner call to `collect_tokens` produces an AST node, and then an outer call to `collect_tokens` produces the same AST node. This can happen in a few places, e.g. expression statements where the statement delegates `HasTokens` and `HasAttrs` to the expression. It will also happen more after #124141.

This PR fixes some double handling cases that cause problems, including #129166.

r? `@petrochenkov`
2024-09-08 05:35:23 +00:00
bors 7f4b270aa4 Auto merge of #129313 - RalfJung:coroutine-niches, r=compiler-errors
Supress niches in coroutines to avoid aliasing violations

As mentioned [here](https://github.com/rust-lang/rust/issues/63818#issuecomment-2264915918), using niches in fields of coroutines that are referenced by other fields is unsound: the discriminant accesses violate the aliasing requirements of the reference pointing to the relevant field. This issue causes [Miri errors in practice](https://github.com/rust-lang/miri/issues/3780).

The "obvious" fix for this is to suppress niches in coroutines. That's what this PR does. However, we have several tests explicitly ensuring that we *do* use niches in coroutines. So I see two options:
- We guard this behavior behind a `-Z` flag (that Miri will set by default). There is no known case of these aliasing violations causing miscompilations. But absence of evidence is not evidence of absence...
- (What this PR does right now.) We temporarily adjust the coroutine layout logic and the associated tests until the proper fix lands. The "proper fix" here is to wrap fields that other fields can point to in [`UnsafePinned`](https://github.com/rust-lang/rust/issues/125735) and make `UnsafePinned` suppress niches; that would then still permit using niches of *other* fields (those that never get borrowed). However, I know that coroutine sizes are already a problem, so I am not sure if this temporary size regression is acceptable.

`@compiler-errors` any opinion? Also who else should be Cc'd here?
2024-09-08 03:11:12 +00:00
EtomicBomb 548b6e197d add tests for behavior in rfc#3662
* Adds tests for the behavior from rfc#3662 in `tests/rustdoc/`
2024-09-07 19:02:22 -04:00
EtomicBomb 2e1cba6415 rfc#3662 changes under unstable flags
* All new functionality is under unstable options
* Adds `--merge=shared|none|finalize` flags
* Adds `--parts-out-dir=<crate specific directory>` for `--merge=none`
to write cross-crate info file for a single crate
* Adds `--include-parts-dir=<previously specified directory>` for
`--merge=finalize` to write cross-crate info files
* update tests/run-make/rustdoc-default-output/rmake.rs golden
2024-09-07 18:59:01 -04:00
Matthias Krüger 04b4523efc
Rollup merge of #130009 - notriddle:notriddle/trailing-arrow, r=lolbinarycat,GuillaumeGomez
rustdoc-search: allow trailing `Foo ->` arg search

Fixes #129710
2024-09-07 23:30:14 +02:00
Matthias Krüger a88b1af7c0
Rollup merge of #129869 - cyrgani:master, r=Mark-Simulacrum
add a few more crashtests

Added them for #123629, #127033 and #129372.
2024-09-07 23:30:13 +02:00
Matthias Krüger 7b7f2f7f74
Rollup merge of #129847 - compiler-errors:async-cycle, r=davidtwco
Do not call query to compute coroutine layout for synthetic body of async closure

There is code in the MIR validator that attempts to prevent query cycles when inlining a coroutine into itself, and will use the coroutine layout directly from the body when it detects that's the same coroutine as the one that's being validated. After #128506, this logic didn't take into account the fact that the coroutine def id will differ if it's the "by-move body" of an async closure. This PR implements that.

Fixes #129811
2024-09-07 23:30:13 +02:00
Matthias Krüger 37523d2a59
Rollup merge of #129677 - compiler-errors:by-move-body-err, r=cjgillot
Don't build by-move body when async closure is tainted

Fixes #129676

See explanation in the ui test.
2024-09-07 23:30:12 +02:00
Matthias Krüger 3b2139bdb1
Rollup merge of #129555 - RalfJung:const_float_bits_conv, r=dtolnay
stabilize const_float_bits_conv

This stabilizes `const_float_bits_conv`, and thus fixes https://github.com/rust-lang/rust/issues/72447. With https://github.com/rust-lang/rust/pull/128596 having landed, this is entirely a libs-only question now.

```rust
impl f32 {
    pub const fn to_bits(self) -> u32;
    pub const fn from_bits(v: u32) -> Self;
    pub const fn to_be_bytes(self) -> [u8; 4];
    pub const fn to_le_bytes(self) -> [u8; 4]
    pub const fn to_ne_bytes(self) -> [u8; 4];
    pub const fn from_be_bytes(bytes: [u8; 4]) -> Self;
    pub const fn from_le_bytes(bytes: [u8; 4]) -> Self;
    pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self;
}

impl f64 {
    pub const fn to_bits(self) -> u64;
    pub const fn from_bits(v: u64) -> Self;
    pub const fn to_be_bytes(self) -> [u8; 8];
    pub const fn to_le_bytes(self) -> [u8; 8]
    pub const fn to_ne_bytes(self) -> [u8; 8];
    pub const fn from_be_bytes(bytes: [u8; 8]) -> Self;
    pub const fn from_le_bytes(bytes: [u8; 8]) -> Self;
    pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self;
}
````

Cc `@rust-lang/wg-const-eval` `@rust-lang/libs-api`
2024-09-07 23:30:11 +02:00
Matthias Krüger ccf3f6e59d
Rollup merge of #126452 - compiler-errors:raw-lifetimes, r=spastorino
Implement raw lifetimes and labels (`'r#ident`)

This PR does two things:
1. Reserve lifetime prefixes, e.g. `'prefix#lt` in edition 2021.
2. Implements raw lifetimes, e.g. `'r#async` in edition 2021.

This PR additionally extends the `keyword_idents_2024` lint to also check lifetimes.

cc `@traviscross`
r? parser
2024-09-07 23:30:10 +02:00
bors ec867f03bc Auto merge of #126161 - Bryanskiy:delegation-generics-4, r=petrochenkov
Delegation: support generics in associated delegation items

This is a continuation of https://github.com/rust-lang/rust/pull/125929.

[design](https://github.com/Bryanskiy/posts/blob/master/delegation%20in%20generic%20contexts.md)

Generic parameters inheritance was implemented in all contexts. Generic arguments are not yet supported.

r? `@petrochenkov`
2024-09-07 18:12:05 +00:00
Tim (Theemathas) Chirananthavat 79b87c57cb Bless tests due to new method suggestions. 2024-09-07 21:06:49 +07:00
Mads Marquart c788dcc674 Test codegen when setting deployment target 2024-09-07 14:06:55 +02:00
Michael Goulet bce7c4b70e Don't build by-move body when async closure is tainted 2024-09-07 07:50:44 -04:00
Michael Goulet 29f31c58e9 Don't call fn_arg_names for non-fn in resolver 2024-09-07 07:38:22 -04:00
Michael Goulet b09b7da010
Rollup merge of #130054 - cuishuang:master, r=chenyukang
Add missing quotation marks
2024-09-07 14:21:23 +03:00
Michael Goulet bc2244f027
Rollup merge of #129940 - liushuyu:s390x-target-features, r=RalfJung
s390x: Fix a regression related to backchain feature

In #127506, we introduced a new IBM Z-specific target feature, `backchain`.

This particular `target-feature` was available as a function-level attribute in LLVM 17 and below, so some hacks were used to avoid blowing up LLVM when querying the supported LLVM features.

This led to an unfortunate regression where `cfg!(target-feature = "backchain")` will always return true.

This pull request aims to fix this issue, and a test has been introduced to ensure it will never happen again.

Fixes #129927.

r? `@RalfJung`
2024-09-07 14:21:22 +03:00
Michael Goulet d6a42983e5
Rollup merge of #129899 - veera-sivarajan:fix-97793-pr-final, r=chenyukang
Add Suggestions for Misspelled Keywords

Fixes #97793

This PR detects misspelled keywords using two heuristics:

1. Lowercasing the unexpected identifier.
2. Using edit distance to find a keyword similar to the unexpected identifier.

However, it does not detect each and every misspelled keyword to
minimize false positives and ambiguities. More details about the
implementation can be found in the comments.
2024-09-07 14:21:22 +03:00
Michael Goulet 6dd07e4e26
Rollup merge of #129891 - nikic:naked-no-san, r=jackh726
Do not request sanitizers for naked functions

Naked functions can only contain inline asm, so any instrumentation inserted by sanitizers is illegal. Don't request it.

Fixes https://github.com/rust-lang/rust/issues/129224.
2024-09-07 14:21:21 +03:00
Michael Goulet 41a20dcb87
Rollup merge of #129840 - GrigorenkoPV:elided-named-lifetimes-suggestion, r=cjgillot
Implement suggestions for `elided_named_lifetimes`

A follow-up to #129207, as per https://github.com/rust-lang/rust/pull/129207#issuecomment-2308992849.

r? cjgillot

I will probably squash this a bit, but later.

`@rustbot` label +A-lint
2024-09-07 14:21:20 +03:00
Michael Goulet adcee23a95
Rollup merge of #129468 - Rajveer100:hack-to-avoid-function-merging, r=Mark-Simulacrum
[testsuite][cleanup] Remove all usages of `dont_merge` hack to avoid function merging

Resolves #129438

The `-Zmerge-functions=disabled` compile flag exists for this purpose.
2024-09-07 14:21:19 +03:00
Folkert de Vries 46115fd6d3 fix ICE in CMSE type validation 2024-09-07 10:53:59 +02:00
Veera 14e86eb7d9 Add Suggestions for Misspelled Keywords
This PR detects misspelled keywords using two heuristics:

1. Lowercasing the unexpected identifier.
2. Using edit distance to find a keyword similar to the unexpected identifier.

However, it does not detect each and every misspelled keyword to
minimize false positives and ambiguities. More details about the
implementation can be found in the comments.
2024-09-06 23:07:45 -04:00
Camille GILLOT 6dfc4033be Do not ICE on expect(warnings). 2024-09-07 01:34:59 +00:00
cuishuang be10d56039 Add missing quotation marks
Signed-off-by: cuishuang <imcusg@gmail.com>
2024-09-07 09:23:28 +08:00
Kyle Huey 7ed9f945a2 Don't leave debug locations for constants sitting on the builder indefinitely.
Because constants are currently emitted *before* the prologue, leaving the
debug location on the IRBuilder spills onto other instructions in the prologue
and messes up both line numbers as well as the point LLVM chooses to be the
prologue end.

Example LLVM IR (irrelevant IR elided):
Before:

define internal { i64, i64 } @_ZN3tmp3Foo18var_return_opt_try17he02116165b0fc08cE(ptr align 8 %self) !dbg !347 {
start:
  %self.dbg.spill = alloca [8 x i8], align 8
  %_0 = alloca [16 x i8], align 8
  %residual.dbg.spill = alloca [0 x i8], align 1
    #dbg_declare(ptr %residual.dbg.spill, !353, !DIExpression(), !357)
  store ptr %self, ptr %self.dbg.spill, align 8, !dbg !357
    #dbg_declare(ptr %self.dbg.spill, !350, !DIExpression(), !358)

After:

define internal { i64, i64 } @_ZN3tmp3Foo18var_return_opt_try17h00b17d08874ddd90E(ptr align 8 %self) !dbg !347 {
start:
  %self.dbg.spill = alloca [8 x i8], align 8
  %_0 = alloca [16 x i8], align 8
  %residual.dbg.spill = alloca [0 x i8], align 1
    #dbg_declare(ptr %residual.dbg.spill, !353, !DIExpression(), !357)
  store ptr %self, ptr %self.dbg.spill, align 8
    #dbg_declare(ptr %self.dbg.spill, !350, !DIExpression(), !358)

Note in particular how !357 from %residual.dbg.spill's dbg_declare no longer
falls through onto the store to %self.dbg.spill. This fixes argument values
at entry when the constant is a ZST (e.g. <Option as Try>::Residual). This
fixes #130003 (but note that it does *not* fix issues with argument values and
non-ZST constants, which emit their own stores that have debug info on them,
like #128945).
2024-09-06 23:12:18 +00:00
Camille GILLOT 94f8347bae Check AttrId for expectations. 2024-09-06 20:51:06 +00:00
Michael Goulet 5054e8cba8 Lint against keyword lifetimes in keyword_idents 2024-09-06 10:32:48 -04:00
Michael Goulet afa24f0180 Add some more tests 2024-09-06 10:32:48 -04:00
Michael Goulet 9aaf873396 Reserve prefix lifetimes too 2024-09-06 10:32:48 -04:00
Pavel Grigorenko 9e2d264fa2 Hack around a conflict with `clippy::needless_lifetimes` 2024-09-06 17:06:35 +03:00
bors 17b322fa69 Auto merge of #121848 - lcnr:stabilize-next-solver, r=compiler-errors
stabilize `-Znext-solver=coherence`

r? `@compiler-errors`

---

This PR stabilizes the use of the next generation trait solver in coherence checking by enabling `-Znext-solver=coherence` by default. More specifically its use in the *implicit negative overlap check*. The tracking issue for this is https://github.com/rust-lang/rust/issues/114862. Closes #114862.

## Background

### The next generation trait solver

The new solver lives in [`rustc_trait_selection::solve`](https://github.com/rust-lang/rust/blob/master/compiler/rustc_trait_selection/src/solve/mod.rs) and is intended to replace the existing *evaluate*, *fulfill*, and *project* implementation. It also has a wider impact on the rest of the type system, for example by changing our approach to handling associated types.

For a more detailed explanation of the new trait solver, see the [rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/solve/trait-solving.html). This does not stabilize the current behavior of the new trait solver, only the behavior impacting the implicit negative overlap check. There are many areas in the new solver which are not yet finalized. We are confident that their final design will not conflict with the user-facing behavior observable via coherence. More on that further down.

Please check out [the chapter](https://rustc-dev-guide.rust-lang.org/solve/significant-changes.html) summarizing the most significant changes between the existing and new implementations.

### Coherence and the implicit negative overlap check

Coherence checking detects any overlapping impls. Overlapping trait impls always error while overlapping inherent impls result in an error if they have methods with the same name. Coherence also results in an error if any other impls could exist, even if they are currently unknown. This affects impls which may get added to upstream crates in a backwards compatible way and impls from downstream crates.

Coherence failing to detect overlap is generally considered to be unsound, even if it is difficult to actually get runtime UB this way. It is quite easy to get ICEs due to bugs in coherence.

It currently consists of two checks:

The [orphan check] validates that impls do not overlap with other impls we do not know about: either because they may be defined in a sibling crate, or because an upstream crate is allowed to add it without being considered a breaking change.

The [overlap check] validates that impls do not overlap with other impls we know about. This is done as follows:
- Instantiate the generic parameters of both impls with inference variables
- Equate the `TraitRef`s of both impls. If it fails there is no overlap.
- [implicit negative]: Check whether any of the instantiated `where`-bounds of one of the impls definitely do not hold when using the constraints from the previous step. If a `where`-bound does not hold, there is no overlap.
- *explicit negative (still unstable, ignored going forward)*: Check whether the any negated `where`-bounds can be proven, e.g. a `&mut u32: Clone` bound definitely does not hold as an explicit `impl<T> !Clone for &mut T` exists.

The overlap check has to *prove that unifying the impls does not succeed*. This means that **incorrectly getting a type error during coherence is unsound** as it would allow impls to overlap: coherence has to be *complete*.

Completeness means that we never incorrectly error. This means that during coherence we must only add inference constraints if they are definitely necessary. During ordinary type checking [this does not hold](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=01d93b592bd9036ac96071cbf1d624a9), so the trait solver has to behave differently, depending on whether we're in coherence or not.

The implicit negative check only considers goals to "definitely not hold" if they could not be implemented downstream, by a sibling, or upstream in a backwards compatible way. If the goal is is "unknowable" as it may get added in another crate, we add an ambiguous candidate: [source](bea5bebf3d/compiler/rustc_trait_selection/src/solve/assembly/mod.rs (L858-L883)).

[orphan check]: fd80c02c16/compiler/rustc_trait_selection/src/traits/coherence.rs (L566-L579)
[overlap check]: fd80c02c16/compiler/rustc_trait_selection/src/traits/coherence.rs (L92-L98)
[implicit negative]: fd80c02c16/compiler/rustc_trait_selection/src/traits/coherence.rs (L223-L281)

## Motivation

Replacing the existing solver in coherence fixes soundness bugs by removing sources of incompleteness in the type system. The new solver separately strengthens coherence, resulting in more impls being disjoint and passing the coherence check. The concrete changes will be elaborated further down. We believe the stabilization to reduce the likelihood of future bugs in coherence as the new implementation is easier to understand and reason about.

It allows us to remove the support for coherence and implicit-negative reasoning in the old solver, allowing us to remove some code and simplifying the old trait solver. We will only remove the old solver support once this stabilization has reached stable to make sure we're able to quickly revert in case any unexpected issues are detected before then.

Stabilizing the use of the next-generation trait solver expresses our confidence that its current behavior is intended and our work towards enabling its use everywhere will not require any breaking changes to the areas used by coherence checking. We are also confident that we will be able to replace the existing solver everywhere, as maintaining two separate systems adds a significant maintainance burden.

## User-facing impact and reasoning

### Breakage due to improved handling of associated types

The new solver fixes multiple issues related to associated types. As these issues caused coherence to consider more types distinct, fixing them results in more overlap errors. This is therefore a breaking change.

#### Structurally relating aliases containing bound vars

Fixes https://github.com/rust-lang/rust/issues/102048. In the existing solver relating ambiguous projections containing bound variables is structural. This is *incomplete* and allows overlapping impls. These was mostly not exploitable as the same issue also caused impls to not apply when trying to use them. The new solver defers alias-relating to a nested goal, fixing this issue:
```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
trait Trait {}

trait Project {
    type Assoc<'a>;
}

impl Project for u32 {
    type Assoc<'a> = &'a u32;
}

// Eagerly normalizing `<?infer as Project>::Assoc<'a>` is ambiguous,
// so the old solver ended up structurally relating
//
//     (?infer, for<'a> fn(<?infer as Project>::Assoc<'a>))
//
// with
//
//     ((u32, fn(&'a u32)))
//
// Equating `&'a u32` with `<u32 as Project>::Assoc<'a>` failed, even
// though these types are equal modulo normalization.
impl<T: Project> Trait for (T, for<'a> fn(<T as Project>::Assoc<'a>)) {}

impl<'a> Trait for (u32, fn(&'a u32)) {}
//[next]~^ ERROR conflicting implementations of trait `Trait` for type `(u32, for<'a> fn(&'a u32))`
```

A crater run did not discover any breakage due to this change.

#### Unknowable candidates for higher ranked trait goals

This avoids an unsoundness by attempting to normalize in `trait_ref_is_knowable`, fixing https://github.com/rust-lang/rust/issues/114061. This is a side-effect of supporting lazy normalization, as that forces us to attempt to normalize when checking whether a `TraitRef` is knowable: [source](47dd709bed/compiler/rustc_trait_selection/src/solve/assembly/mod.rs (L754-L764)).

```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
trait IsUnit {}
impl IsUnit for () {}

pub trait WithAssoc<'a> {
    type Assoc;
}

// We considered `for<'a> <T as WithAssoc<'a>>::Assoc: IsUnit`
// to be knowable, even though the projection is ambiguous.
pub trait Trait {}
impl<T> Trait for T
where
    T: 'static,
    for<'a> T: WithAssoc<'a>,
    for<'a> <T as WithAssoc<'a>>::Assoc: IsUnit,
{
}
impl<T> Trait for Box<T> {}
//[next]~^ ERROR conflicting implementations of trait `Trait`
```
The two impls of `Trait` overlap given the following downstream crate:
```rust
use dep::*;
struct Local;
impl WithAssoc<'_> for Box<Local> {
    type Assoc = ();
}
```

There a similar coherence unsoundness caused by our handling of aliases which is fixed separately in https://github.com/rust-lang/rust/pull/117164.

This change breaks the [`derive-visitor`](https://crates.io/crates/derive-visitor) crate. I have opened an issue in that repo: nikis05/derive-visitor#16.

### Evaluating goals to a fixpoint and applying inference constraints

In the old implementation of the implicit-negative check, each obligation is [checked separately without applying its inference constraints](bea5bebf3d/compiler/rustc_trait_selection/src/traits/coherence.rs (L323-L338)). The new solver instead [uses a `FulfillmentCtxt`](bea5bebf3d/compiler/rustc_trait_selection/src/traits/coherence.rs (L315-L321)) for this, which evaluates all obligations in a loop until there's no further inference progress.

This is necessary for backwards compatibility as we do not eagerly normalize with the new solver, resulting in constraints from normalization to only get applied by evaluating a separate obligation. This also allows more code to compile:
```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
trait Mirror {
    type Assoc;
}
impl<T> Mirror for T {
    type Assoc = T;
}

trait Foo {}
trait Bar {}

// The self type starts out as `?0` but is constrained to `()`
// due to the where-clause below. Because `(): Bar` is known to
// not hold, we can prove the impls disjoint.
impl<T> Foo for T where (): Mirror<Assoc = T> {}
//[current]~^ ERROR conflicting implementations of trait `Foo` for type `()`
impl<T> Foo for T where T: Bar {}

fn main() {}
```
The old solver does not run nested goals to a fixpoint in evaluation. The new solver does do so, strengthening inference and improving the overlap check:
```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
trait Foo {}
impl<T> Foo for (u8, T, T) {}
trait NotU8 {}
trait Bar {}
impl<T, U: NotU8> Bar for (T, T, U) {}

trait NeedsFixpoint {}
impl<T: Foo + Bar> NeedsFixpoint for T {}
impl NeedsFixpoint for (u8, u8, u8) {}

trait Overlap {}
impl<T: NeedsFixpoint> Overlap for T {}
impl<T, U: NotU8, V> Overlap for (T, U, V) {}
//[current]~^ ERROR conflicting implementations of trait `Foo`
```

### Breakage due to removal of incomplete candidate preference

Fixes #107887. In the old solver we incompletely prefer the builtin trait object impl over user defined impls. This can break inference guidance, inferring `?x` in `dyn Trait<u32>: Trait<?x>` to `u32`, even if an explicit impl of `Trait<u64>` also exists.

This caused coherence to incorrectly allow overlapping impls, resulting in ICEs and a theoretical unsoundness. See https://github.com/rust-lang/rust/issues/107887#issuecomment-1997261676. This compiles on stable but results in an overlap error with `-Znext-solver=coherence`:

```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
struct W<T: ?Sized>(*const T);

trait Trait<T: ?Sized> {
    type Assoc;
}

// This would trigger the check for overlap between automatic and custom impl.
// They actually don't overlap so an impl like this should remain possible
// forever.
//
// impl Trait<u64> for dyn Trait<u32> {}
trait Indirect {}
impl Indirect for dyn Trait<u32, Assoc = ()> {}
impl<T: Indirect + ?Sized> Trait<u64> for T {
    type Assoc = ();
}

// Incomplete impl where `dyn Trait<u32>: Trait<_>` does not hold, but
// `dyn Trait<u32>: Trait<u64>` does.
trait EvaluateHack<U: ?Sized> {}
impl<T: ?Sized, U: ?Sized> EvaluateHack<W<U>> for T
where
    T: Trait<U, Assoc = ()>, // incompletely constrains `_` to `u32`
    U: IsU64,
    T: Trait<U, Assoc = ()>, // incompletely constrains `_` to `u32`
{
}

trait IsU64 {}
impl IsU64 for u64 {}

trait Overlap<U: ?Sized> {
    type Assoc: Default;
}
impl<T: ?Sized + EvaluateHack<W<U>>, U: ?Sized> Overlap<U> for T {
    type Assoc = Box<u32>;
}
impl<U: ?Sized> Overlap<U> for dyn Trait<u32, Assoc = ()> {
//[next]~^ ERROR conflicting implementations of trait `Overlap<_>`
    type Assoc = usize;
}
```

### Considering region outlives bounds in the `leak_check`

For details on the `leak_check`, see the FCP proposal in #119820.[^leak_check]

[^leak_check]: which should get moved to the dev-guide once that PR lands :3

In both coherence and during candidate selection, the `leak_check` relies on the region constraints added in `evaluate`. It therefore currently does not register outlives obligations: [source](ccb1415eac/compiler/rustc_trait_selection/src/traits/select/mod.rs (L792-L810)). This was likely done as a performance optimization without considering its impact on the `leak_check`. This is the case as in the old solver, *evaluatation* and *fulfillment* are split, with evaluation being responsible for candidate selection and fulfillment actually registering all the constraints.

This split does not exist with the new solver. The `leak_check` can therefore eagerly detect errors caused by region outlives obligations. This improves both coherence itself and candidate selection:

```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
trait LeakErr<'a, 'b> {}
// Using this impl adds an `'b: 'a` bound which results
// in a higher-ranked region error. This bound has been
// previously ignored but is now considered.
impl<'a, 'b: 'a> LeakErr<'a, 'b> for () {}

trait NoOverlapDir<'a> {}
impl<'a, T: for<'b> LeakErr<'a, 'b>> NoOverlapDir<'a> for T {}
impl<'a> NoOverlapDir<'a> for () {}
//[current]~^ ERROR conflicting implementations of trait `NoOverlapDir<'_>`

// --------------------------------------

// necessary to avoid coherence unknowable candidates
struct W<T>(T);

trait GuidesSelection<'a, U> {}
impl<'a, T: for<'b> LeakErr<'a, 'b>> GuidesSelection<'a, W<u32>> for T {}
impl<'a, T> GuidesSelection<'a, W<u8>> for T {}

trait NotImplementedByU8 {}
trait NoOverlapInd<'a, U> {}
impl<'a, T: GuidesSelection<'a, W<U>>, U> NoOverlapInd<'a, U> for T {}
impl<'a, U: NotImplementedByU8> NoOverlapInd<'a, U> for () {}
//[current]~^ conflicting implementations of trait `NoOverlapInd<'_, _>`
```

### Removal of `fn match_fresh_trait_refs`

The old solver tries to [eagerly detect unbounded recursion](b14fd2359f/compiler/rustc_trait_selection/src/traits/select/mod.rs (L1196-L1211)), forcing the affected goals to be ambiguous. This check is only an approximation and has not been added to the new solver.

The check is not necessary in the new solver and it would be problematic for caching. As it depends on all goals currently on the stack, using a global cache entry would have to always make sure that doing so does not circumvent this check.

This changes some goals to error - or succeed - instead of failing with ambiguity. This allows more code to compile:

```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence

// Need to use this local wrapper for the impls to be fully
// knowable as unknowable candidate result in ambiguity.
struct Local<T>(T);

trait Trait<U> {}
// This impl does not hold, but is ambiguous in the old
// solver due to its overflow approximation.
impl<U> Trait<U> for Local<u32> where Local<u16>: Trait<U> {}
// This impl holds.
impl Trait<Local<()>> for Local<u8> {}

// In the old solver, `Local<?t>: Trait<Local<?u>>` is ambiguous,
// resulting in `Local<?u>: NoImpl`, also being ambiguous.
//
// In the new solver the first impl does not apply, constraining
// `?u` to `Local<()>`, causing `Local<()>: NoImpl` to error.
trait Indirect<T> {}
impl<T, U> Indirect<U> for T
where
    T: Trait<U>,
    U: NoImpl
{}

// Not implemented for `Local<()>`
trait NoImpl {}
impl NoImpl for Local<u8> {}
impl NoImpl for Local<u16> {}

// `Local<?t>: Indirect<Local<?u>>` cannot hold, so
// these impls do not overlap.
trait NoOverlap<U> {}
impl<T: Indirect<U>, U> NoOverlap<U> for T {}
impl<T, U> NoOverlap<Local<U>> for Local<T> {}
//~^ ERROR conflicting implementations of trait `NoOverlap<Local<_>>`
```

### Non-fatal overflow

The old solver immediately emits a fatal error when hitting the recursion limit. The new solver instead returns overflow. This both allows more code to compile and is results in performance and potential future compatability issues.

Non-fatal overflow is generally desirable. With fatal overflow, changing the order in which we evaluate nested goals easily causes breakage if we have goal which errors and one which overflows. It is also required to prevent breakage due to the removal of `fn match_fresh_trait_refs`, e.g. [in `typenum`](https://github.com/rust-lang/trait-system-refactor-initiative/issues/73).

#### Enabling more code to compile

In the below example, the old solver first tried to prove an overflowing goal, resulting in a fatal error. The new solver instead returns ambiguity due to overflow for that goal, causing the implicit negative overlap check to succeed as `Box<u32>: NotImplemented` does not hold.
```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
//[current] ERROR overflow evaluating the requirement

trait Indirect<T> {}
impl<T: Overflow<()>> Indirect<T> for () {}

trait Overflow<U> {}
impl<T, U> Overflow<U> for Box<T>
where
    U: Indirect<Box<Box<T>>>,
{}

trait NotImplemented {}

trait Trait<U> {}
impl<T, U> Trait<U> for T
where
    // T: NotImplemented, // causes old solver to succeed
    U: Indirect<T>,
    T: NotImplemented,
{}

impl Trait<()> for Box<u32> {}
```

#### Avoiding hangs with non-fatal overflow

Simply returning ambiguity when reaching the recursion limit can very easily result in hangs, e.g.
```rust
trait Recur {}
impl<T, U> Recur for ((T, U), (U, T))
where
    (T, U): Recur,
    (U, T): Recur,
{}

trait NotImplemented {}
impl<T: NotImplemented> Recur for T {}
```
This can happen quite frequently as it's easy to have exponential blowup due to multiple nested goals at each step. As the trait solver is depth-first, this immediately caused a fatal overflow error in the old solver. In the new solver we have to handle the whole proof tree instead, which can very easily hang.

To avoid this we restrict the recursion depth after hitting the recursion limit for the first time. We also **ignore all inference constraints from goals resulting in overflow**. This is mostly backwards compatible as any overflow in the old solver resulted in a fatal error.

### sidenote about normalization

We return ambiguous nested goals of `NormalizesTo` goals to the caller and ignore their impact when computing the `Certainty` of the current goal. See the [normalization chapter](https://rustc-dev-guide.rust-lang.org/solve/normalization.html) for more details.This means we apply constraints resulting from other nested goals and from equating the impl header when normalizing, even if a nested goal results in overflow. This is necessary to avoid breaking the following example:
```rust
trait Trait {
    type Assoc;
}

struct W<T: ?Sized>(*mut T);
impl<T: ?Sized> Trait for W<W<T>>
where
    W<T>: Trait,
{
    type Assoc = ();
}

// `W<?t>: Trait<Assoc = u32>` does not hold as
// `Assoc` gets normalized to `()`. However, proving
// the where-bounds of the impl results in overflow.
//
// For this to continue to compile we must not discard
// constraints from normalizing associated types.
trait NoOverlap {}
impl<T: Trait<Assoc = u32>> NoOverlap for T {}
impl<T: ?Sized> NoOverlap for W<T> {}
```

#### Future compatability concerns

Non-fatal overflow results in some unfortunate future compatability concerns. Changing the approach to avoid more hangs by more strongly penalizing overflow can cause breakage as we either drop constraints or ignore candidates necessary to successfully compile. Weakening the overflow penalities instead allows more code to compile and strengthens inference while potentially causing more code to hang.

While the current approach is not perfect, we believe it to be good enough. We believe it to apply the necessary inference constraints to avoid breakage and expect there to not be any desirable patterns broken by our current penalities. Similarly we believe the current constraints to avoid most accidental hangs. Ignoring constraints of overflowing goals is especially useful, as it may allow major future optimizations to our overflow handling. See [this summary](https://hackmd.io/ATf4hN0NRY-w2LIVgeFsVg) and the linked documents in case you want to know more.

### changes to performance

In general, trait solving during coherence checking is not significant for performance. Enabling the next-generation trait solver in coherence does not impact our compile time benchmarks. We are still unable to compile the benchmark suite when fully enabling the new trait solver.

There are rare cases where the new solver has significantly worse performance due to non-fatal overflow, its reliance on fixpoint algorithms and the removal of the `fn match_fresh_trait_refs` approximation. We encountered such issues in [`typenum`](https://crates.io/crates/typenum) and believe it should be [pretty much as bad as it can get](https://github.com/rust-lang/trait-system-refactor-initiative/issues/73).

Due to an improved structure and far better caching, we believe that there is a lot of room for improvement and that the new solver will outperform the existing implementation in nearly all cases, sometimes significantly. We have not yet spent any time micro-optimizing the implementation and have many unimplemented major improvements, such as fast-paths for trivial goals.

TODO: get some rough results here and put them in a table

### Unstable features

#### Unsupported unstable features

The new solver currently does not support all unstable features, most notably `#![feature(generic_const_exprs)]`, `#![feature(associated_const_equality)]` and `#![feature(adt_const_params)]` are not yet fully supported in the new solver. We are confident that supporting them is possible, but did not consider this to be a priority. This stabilization introduces new ICE when using these features in impl headers.

#### fixes to `#![feature(specialization)]`

- fixes #105782
- fixes #118987

#### fixes to `#![feature(type_alias_impl_trait)]`

- fixes #119272
- https://github.com/rust-lang/rust/issues/105787#issuecomment-1750112388
- fixes #124207

## This does not stabilize the whole solver

While this stabilizes the use of the new solver in coherence checking, there are many parts of the solver which will remain fully unstable. We may still adapt these areas while working towards stabilizing the new solver everywhere. We are confident that we are able to do so without negatively impacting coherence.

### goals with a non-empty `ParamEnv`

Coherence always uses an empty environment. We therefore do not depend on the behavior of `AliasBound` and `ParamEnv` candidates. We only stabilizes the behavior of user-defined and builtin implementations of traits. There are still many open questions there.

### opaque types in the defining scope

The handling of opaque types - `impl Trait` - in both the new and old solver is still not fully figured out. Luckily this can be ignored for now. While opaque types are reachable during coherence checking by using `impl_trait_in_associated_types`, the behavior during coherence is separate and self-contained. The old and new solver fully agree here.

### normalization is hard

This stabilizes that we equate associated types involving bound variables using deferred-alias-equality. We also stop eagerly normalizing in coherence, which should not have any user-facing impact.

We do not stabilize the normalization behavior outside of coherence, e.g. we currently deeply normalize all types during writeback with the new solver. This may change going forward

### how to replace `select` from the old solver

We sometimes depend on getting a single `impl` for a given trait bound, e.g. when resolving a concrete method for codegen/CTFE. We do not depend on this during coherence, so the exact approach here can still be freely changed going forward.

## Acknowledgements

This work would not have been possible without `@compiler-errors.` He implemented large chunks of the solver himself but also and did a lot of testing and experimentation, eagerly discovering multiple issues which had a significant impact on our approach. `@BoxyUwU` has also done some amazing work on the solver. Thank you for the endless hours of discussion resulting in the current approach. Especially the way aliases are handled has gone through multiple revisions to get to its current state.

There were also many contributions from - and discussions with - other members of the community and the rest of `@rust-lang/types.` This solver builds upon previous improvements to the compiler, as well as lessons learned from `chalk` and `a-mir-formality`. Getting to this point  would not have been possible without that and I am incredibly thankful to everyone involved. See the [list of relevant PRs](https://github.com/rust-lang/rust/pulls?q=is%3Apr+is%3Amerged+label%3AWG-trait-system-refactor+-label%3Arollup+closed%3A%3C2024-03-22+).
2024-09-06 13:12:14 +00:00
Pavel Grigorenko 547db4a4b7 elided_named_lifetimes: manually implement `LintDiagnostic` 2024-09-06 15:47:52 +03:00
Pavel Grigorenko dcfc71310d elided_named_lifetimes: add suggestions 2024-09-06 15:47:52 +03:00
Nikita Popov 54ebb9d489 Do not request sanitizers for naked functions
Naked functions can only contain inline asm, so any instrumentation
inserted by sanitizers is illegal. Don't request it.

Fixes https://github.com/rust-lang/rust/issues/129224.
2024-09-06 14:11:13 +02:00
Urgau 7dd1be1d0d Also emit `missing_docs` lint with `--test` to fulfill expectations 2024-09-06 12:20:36 +02:00
Matthias Krüger 11d5614a74
Rollup merge of #130013 - jonathan-conder:await_coverage, r=Zalathar
coverage: Count await when the Future is immediately ready

Currently `await` is only counted towards coverage if the containing
function is suspended and resumed at least once. This is because it
expands to code which contains a branch on the discriminant of `Poll`.

By treating it like a branching macro (e.g. `assert!`), these
implementation details will be hidden from the coverage results.

I added a test to ensure the fix works in simple cases, but the heuristic of picking only the first await-related covspan might be unreliable. I plan on testing more thoroughly with a real codebase over the next couple of weeks.

closes #98712
2024-09-06 07:33:59 +02:00
Matthias Krüger e903b29dc3
Rollup merge of #129021 - compiler-errors:ptr-cast-outlives, r=lcnr
Check WF of source type's signature on fn pointer cast

This PR patches the implied bounds holes slightly for #129005, #25860.

Like most implied bounds related unsoundness fixes, this isn't complete w.r.t. higher-ranked function signatures, but I believe it implements a pretty good heuristic for now.

### What does this do?

This PR makes a partial patch for a soundness hole in a `FnDef` -> `FnPtr` "reifying" pointer cast where we were never checking that the signature we are casting *from* is actually well-formed. Because of this, and because `FnDef` doesn't require its signature to be well-formed (just its predicates must hold), we are essentially allowed to "cast away" implied bounds that are assumed within the body of the `FnDef`:

```
fn foo<'a, 'b, T>(_: &'a &'b (), v: &'b T) -> &'a T { v }

fn bad<'short, T>(x: &'short T) -> &'static T {
    let f: fn(_, &'short T) -> &'static T = foo;
    f(&&(), x)
}
```

In this example, subtyping ends up casting the `_` type (which should be `&'static &'short ()`) to some other type that no longer serves as a "witness" to the lifetime relationship `'short: 'static` which would otherwise be required for this call to be WF. This happens regardless of if `foo`'s lifetimes are early- or late-bound.

This PR implements two checks:
1. We check that the signature of the `FnDef` is well-formed *before* casting it. This ensures that there is at least one point in the MIR where we ensure that the `FnDef`'s implied bounds are actually satisfied by the caller.
2. Implements a special case where if we're casting from a higher-ranked `FnDef` to a non-higher-ranked, we instantiate the binder of the `FnDef` with *infer vars* and ensure that it is a supertype of the target of the cast.

The (2.) is necessary to validate that these pointer casts are valid for higher-ranked `FnDef`. Otherwise, the example above would still pass even if `help`'s `'a` lifetime were late-bound.

### Further work

The WF checks for function calls are scattered all over the MIR. We check the WF of args in call terminators, we check the WF of `FnDef` when we create a `const` operand referencing it, and we check the WF of the return type in #115538, to name a few.

One way to make this a bit cleaner is to simply extend #115538 to always check that the signature is WF for `FnDef` types. I may do this as a follow-up, but I wanted to keep this simple since this leads to some pretty bad NLL diagnostics regressions, and AFAICT this solution is *complete enough*.

### Crater triage

Done here: https://github.com/rust-lang/rust/pull/129021#issuecomment-2297702647

r? lcnr
2024-09-06 07:33:56 +02:00
Jonathan Conder 25d183057e coverage: Treat await similar to a macro
Currently `await` is only counted towards coverage if the containing
function is suspended and resumed at least once. This is because it
expands to code which contains a branch on the discriminant of `Poll`.

By treating it like a branching macro (e.g. `assert!`), these
implementation details will be hidden from the coverage results.
2024-09-06 17:01:59 +12:00
Jonathan Conder 3446ca535e coverage: Add test to codify existing behavior
Currently `await` is only counted towards coverage if the containing
function is suspended and resumed at least once. A future commit will
fix this and update the test to reflect the new behavior.
2024-09-06 16:50:23 +12:00
bors d678b81485 Auto merge of #129999 - matthiaskrgr:rollup-pzr9c8p, r=matthiaskrgr
Rollup of 11 pull requests

Successful merges:

 - #128919 (Add an internal lint that warns when accessing untracked data)
 - #129472 (fix ICE when `asm_const` and `const_refs_to_static` are combined)
 - #129653 (clarify that addr_of creates read-only pointers)
 - #129775 (bootstrap: Try to track down why `initial_libdir` sometimes fails)
 - #129939 (explain why Rvalue::Len still exists)
 - #129942 (copy rustc rustlib artifacts from ci-rustc)
 - #129943 (use the bootstrapped compiler for `test-float-parse` test)
 - #129944 (Add compat note for trait solver change)
 - #129947 (Add digit separators in `Duration` examples)
 - #129955 (Temporarily remove fmease from the review rotation)
 - #129957 (forward linker option to lint-docs)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-09-06 03:06:52 +00:00
Michael Howell 3699e939e8 rustdoc-search: allow trailing `Foo ->` arg search 2024-09-05 17:58:05 -07:00
bors 54fdef7799 Auto merge of #121614 - clubby789:no-expect, r=saethlin
Don't emit `expect`/`assume` in opt-level=0

LLVM does not make use of expect/assume calls in `opt-level=0`, so we can simplify IR by not emitting them in this case.
2024-09-06 00:42:58 +00:00
Matthias Krüger 3daa015f82
Rollup merge of #129472 - folkertdev:const-refs-to-static-asm-const, r=lcnr
fix ICE when `asm_const` and `const_refs_to_static` are combined

fixes https://github.com/rust-lang/rust/issues/129462
fixes #126896
fixes #124164

I think this is a case that was missed in the fix for https://github.com/rust-lang/rust/pull/125558, which inserts a type error in the case of an invalid (that is, non-integer) type being passed to an asm `const` operand.

I'm not 100% sure that `span_mirbug_and_err` is the right macro here, but it is used earlier with `builtin_deref` and seems to do the trick.

r? ``@lcnr``
2024-09-05 19:43:46 +02:00
Matthias Krüger 46f390f047
Rollup merge of #128919 - Nadrieril:lint-query-leaks, r=cjgillot
Add an internal lint that warns when accessing untracked data

Some methods access data that is not tracked by the query system and should be used with caution. As suggested in https://github.com/rust-lang/rust/pull/128815#issuecomment-2275488683, in this PR I propose a lint (modeled on the `potential_query_instability` lint) that warns when using some specially-annotatted functions.

I can't tell myself if this lint would be that useful, compared to renaming `Steal::is_stolen` to `is_stolen_untracked`. This would depend on whether there are other functions we'd want to lint like this. So far it seems they're called `*_untracked`, which may be clear enough.

r? ``@oli-obk``
2024-09-05 19:43:46 +02:00
Matthias Krüger fee6c0a683
Rollup merge of #129973 - jieyouxu:rework-rmake-stdio, r=Kobzol
run_make_support: rename `Command::stdin` to `stdin_buf` and add `std{in,out,err}` config helpers

Previously `Command::stdin` was actually just a stdin buffer helper, but
this is different from `std::process::Command::stdin`. This is
needlessly confusing, and blocks support to add `std{in,out,err}` config
helpers that tests may want to use to e.g. redirect to `/dev/ptmx`.
2024-09-05 18:58:57 +02:00
Matthias Krüger 9be97ae8e2
Rollup merge of #129796 - GuillaumeGomez:unify-code-examples, r=notriddle
Unify scraped examples with other code examples

Fixes #129763.

This first PR both fixes #129763 but also unifies buttons display for code examples:

![image](https://github.com/user-attachments/assets/c8475945-dcc3-4c25-8d7d-1659f85301c8)

You can test it [here](https://rustdoc.crud.net/imperio/unify-code-examples/doc/scrape_examples/fn.test.html) and [here](https://rustdoc.crud.net/imperio/unify-code-examples/doc/scrape_examples/fn.test_many.html).

I'm planning to send a follow-up to make the buttons generated in JS directly (or I can do it in this PR directly if you prefer).

cc ```@willcrichton```
r? ```@notriddle```
2024-09-05 18:58:56 +02:00
Matthias Krüger 11085aa73a
Rollup merge of #129706 - compiler-errors:scratch, r=estebank
Rename dump of coroutine by-move-body to be more consistent, fix ICE in dump_mir

First, we add a missing match for `DefKind::SyntheticCoroutineBody` in `dump_mir`. Fixes #129703. The second commit (directly below) serves as a test.

Second, we reorder the `dump_mir` in `coroutine_by_move_body_def_id` to be *after* we adjust the body source, and change the disambiguator so it reads more like any other MIR body. This also serves as a test for the ICE, since we're dumping the MIR of a body with `DefKind::SyntheticCoroutineBody`.

Third, we change the parenting of the synthetic MIR body to have the *coroutine-closure* (i.e. async closure) as its parent, so we don't have long strings of `{closure#0}-{closure#0}-{closure#0}`.

try-job: test-various
2024-09-05 18:58:55 +02:00
Matthias Krüger 6a23ee5595
Rollup merge of #129471 - GuillaumeGomez:sort-impl-associated-items, r=t-rustdoc-frontend
[rustdoc] Sort impl associated items by kinds and then by appearance

Following [this zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/266220-t-rustdoc/topic/.22Freeze.22.20order.20of.20items.20in.20.28trait.29.20impls.3F), I implemented it.

This brings the following change: impl associated items will now be grouped by kind and will now be first sorted by kind and then by the order they are declared in the source code (like currently).

The kinds are sorted in the following order:
1. Constants
2. Types
3. Functions

The reason behind this order is that associated constants can be used in associated types (like length in arrays) and both associated types and associated constants can be used in associated functions. So if an associated item from the same impl is used, its definition will always be above where it's being used.

cc ``@camelid``
r? ``@notriddle``
2024-09-05 18:58:54 +02:00
arnaudgolfouse 13d56dc160 Use a `Vec` in `rustc_interface::Config::locale_resources`
This allows a third-party tool to injects its own resources,
when receiving the config via `rustc_driver::Callbacks::config`.
2024-09-05 16:49:38 +02:00