Commit graph

7287 commits

Author SHA1 Message Date
Oneirical 22953b3f52 convert simple-dylib to ui test 2024-05-29 11:34:39 -04:00
Alice Ryhl 4aafecb169 Simplify check for unsupported architectures 2024-05-29 16:58:46 +02:00
bors a83f933a9d Auto merge of #125531 - surechen:make_suggestion_for_note_like_drop_lint, r=Urgau
Make lint: `lint_dropping_references` `lint_forgetting_copy_types` `lint_forgetting_references` give suggestion if possible.

This is a follow-up PR of  #125433. When it's merged, I want change lint `dropping_copy_types` to use the same `Subdiagnostic` struct `UseLetUnderscoreIgnoreSuggestion` which is added in this PR.

Hi, Thank you(`@Urgau` ) again for your help in the previous PR.  If your time permits, please also take a look at this one.

r? compiler

<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.

This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using

    r​? <reviewer name>
-->
2024-05-29 14:05:30 +00:00
Chris Denton 1e6544a20e
Move run-make windows_subsystem tests to ui tests 2024-05-29 13:04:28 +00:00
Zalathar 34a1828fea coverage: Add tests for the MC/DC condition limit 2024-05-29 20:12:20 +10:00
Oli Scherer a34c26e7ec Make body_owned_by return the body directly.
Almost all callers want this anyway, and now we can use it to also return fed bodies
2024-05-29 10:04:08 +00:00
Daria Sukhonina 4903cf4df6 Revert miri async drop test but add warnings to each async drop test 2024-05-29 12:57:01 +03:00
Daria Sukhonina 57a44b2119 Bless new async destructor sizes in async drop tests 2024-05-29 12:57:01 +03:00
Daria Sukhonina e0904cd6a9 Add size check inside of the async drop tests 2024-05-29 12:50:44 +03:00
bors 4cf5723dbe Auto merge of #125695 - RalfJung:fn_arg_sanity_check, r=jieyouxu
fn_arg_sanity_check: fix panic message

The `\n` inside a raw string doesn't actually make a newline...
2024-05-29 09:49:23 +00:00
surechen ac736d6d88 Let lint_forgetting_references give the suggestion if possible 2024-05-29 17:40:34 +08:00
Oli Scherer 39b39da40b Stop proving outlives constraints on regions we already reported errors on 2024-05-29 09:27:07 +00:00
surechen d7f0d1f564 Let lint_forgetting_copy_types give the suggestion if possible. 2024-05-29 16:53:37 +08:00
surechen ca68c93135 Let lint_dropping_references give the suggestion if possible. 2024-05-29 16:53:28 +08:00
Oli Scherer bcfefe1c7e Reintroduce name resolution check for trying to access locals from an inline const 2024-05-29 08:28:44 +00:00
Ralf Jung 92af72d192 fn_arg_sanity_check: fix panic message
also update csky comment in abi/compatibility test
2024-05-29 08:16:47 +02:00
bors 5870f1ccbb Auto merge of #125433 - surechen:fix_125189, r=Urgau
A small diagnostic improvement for dropping_copy_types

For a value `m`  which implements `Copy` trait, `drop(m);` does nothing.
We now suggest user to ignore it by a abstract and general note: `let _ = ...`.
I think we can give a clearer note here: `let _ = m;`

fixes #125189

<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.

This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using

    r​? <reviewer name>
-->
2024-05-29 06:14:05 +00:00
许杰友 Jieyou Xu (Joe) 7e93a632a8
Rollup merge of #125638 - Oneirical:lets-find-some-tests, r=jieyouxu
Rewrite `lto-smoke`, `simple-rlib` and `mixing-deps` `run-make` tests in `rmake.rs` format

Part of #121876 and the associated [Google Summer of Code project](https://blog.rust-lang.org/2024/05/01/gsoc-2024-selected-projects.html).
2024-05-29 03:25:10 +01:00
许杰友 Jieyou Xu (Joe) bc1a069ec5
Rollup merge of #125381 - estebank:issue-96799, r=petrochenkov
Silence some resolve errors when there have been glob import errors

When encountering `use foo::*;` where `foo` fails to be found, and we later encounter resolution errors, we silence those later errors.

A single case of the above, for an *existing* import on a big codebase would otherwise have a huge number of knock-down spurious errors.

Ideally, instead of a global flag to silence all subsequent resolve errors, we'd want to introduce an unnameable binding in the appropriate rib as a sentinel when there's a failed glob import, so when we encounter a resolve error we can search for that sentinel and if found, and only then, silence that error. The current approach is just a quick proof of concept to iterate over.

Partially address #96799.
2024-05-29 03:25:08 +01:00
许杰友 Jieyou Xu (Joe) 3cc59aeaae
Rollup merge of #125226 - madsmtm:fix-mac-catalyst-tests, r=workingjubilee
Make more of the test suite run on Mac Catalyst

Combined with https://github.com/rust-lang/rust/pull/125225, the only failing parts of the test suite are in `tests/rustdoc-js`, `tests/rustdoc-js-std` and `tests/debuginfo`. Tested with:
```console
./x test --target=aarch64-apple-ios-macabi library/std
./x test --target=aarch64-apple-ios-macabi --skip=tests/rustdoc-js --skip=tests/rustdoc-js-std --skip=tests/debuginfo tests
```

Will probably put up a PR later to enable _running_ on (not just compiling for) Mac Catalyst in CI, though not sure where exactly I should do so? `src/ci/github-actions/jobs.yml`?

Note that I've deliberately _not_ enabled stack overflow handlers on iOS/tvOS/watchOS/visionOS (see https://github.com/rust-lang/rust/issues/25872), but rather just skipped those tests, as it uses quite a few APIs that I'd be weary about getting rejected by the App Store (note that Swift doesn't do it on those platforms either).

r? ``@workingjubilee``

CC ``@thomcc``

``@rustbot`` label O-ios O-apple
2024-05-29 03:25:08 +01:00
许杰友 Jieyou Xu (Joe) 7e441a11a1
Rollup merge of #124320 - Urgau:print-check-cfg, r=petrochenkov
Add `--print=check-cfg` to get the expected configs

This PR adds a new `--print` variant `check-cfg` to get the expected configs.

Details and rational can be found on the MCP: https://github.com/rust-lang/compiler-team/issues/743

``@rustbot`` label +F-check-cfg +S-waiting-on-MCP
r? ``@petrochenkov``
2024-05-29 03:25:07 +01:00
Oneirical cc97376ade Rewrite simple-rlib to rmake 2024-05-28 11:41:53 -04:00
Esteban Küber 37c54db477 Silence some resolve errors when there have been glob import errors
When encountering `use foo::*;` where `foo` fails to be found, and we later
encounter resolution errors, we silence those later errors.

A single case of the above, for an *existing* import on a big codebase would
otherwise have a huge number of knock-down spurious errors.

Ideally, instead of a global flag to silence all subsequent resolve errors,
we'd want to introduce an unameable binding in the appropriate rib as a
sentinel when there's a failed glob import, so when we encounter a resolve
error we can search for that sentinel and if found, and only then, silence
that error. The current approach is just a quick proof of concept to
iterate over.

Partially address #96799.
2024-05-28 14:45:21 +00:00
Oli Scherer ddc5f9b6c1 Create const block DefIds in typeck instead of ast lowering 2024-05-28 13:38:43 +00:00
Oli Scherer a04ac26a9d Allow type_of to return partially non-error types if the type was already tainted 2024-05-28 11:55:20 +00:00
Mads Marquart e6b9bb7b72 Make more of the test suite run on Mac Catalyst
This adds the `only-apple`/`ignore-apple` compiletest directive, and
uses that basically everywhere instead of `only-macos`/`ignore-macos`.

Some of the updates in `run-make` are a bit redundant, as they use
`ignore-cross-compile` and won't run on iOS - but using Apple in these
is still more correct, so I've made that change anyhow.
2024-05-28 12:31:33 +02:00
Mads Marquart 37ae2b68b1 Disable stack overflow handler tests on iOS-like platforms 2024-05-28 12:31:12 +02:00
Mads Marquart d82be822a8 Enable a few tests on macOS 2024-05-28 12:31:12 +02:00
Jubilee 01aa2e8511
Rollup merge of #125640 - fmease:plz-no-stringify, r=estebank
Don't suggest turning non-char-literal exprs of ty `char` into string literals

Fixes #125595.
Fixes #125081.

r? estebank (#122217) or compiler
2024-05-28 02:07:48 -07:00
Jubilee fb95fda87f
Rollup merge of #125343 - lcnr:eagerly-normalize-added-goals, r=compiler-errors
`-Znext-solver`: eagerly normalize when adding goals

fixes #125269. I am not totally with this fix and going to keep this open until we have a more general discussion about how to handle hangs caused by lazy norm in the new solver.
2024-05-28 02:07:47 -07:00
Jubilee 8e89f83cbb
Rollup merge of #125089 - Urgau:non_local_def-suggestions, r=estebank
Improve diagnostic output the `non_local_definitions` lint

This PR improves (or at least tries to improve) the diagnostic output the `non_local_definitions` lint, by simplifying the wording, by adding a "sort of" explanation of bounds interaction that leak the impl...

This PR is best reviewed commit by commit and is voluntarily made a bit vague as to have a starting point to improve on.

Related to https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/non_local_defs.20wording.20improvements

Fixes https://github.com/rust-lang/rust/issues/125068
Fixes https://github.com/rust-lang/rust/issues/124396
cc ```@workingjubilee```
r? ```@estebank```
2024-05-28 02:07:47 -07:00
León Orell Valerian Liehr 27cdc0df4e
Don't suggest turning non-char-literal exprs of ty char into string literals 2024-05-28 09:40:02 +02:00
lcnr 98bfd54b0a eagerly normalize when adding goals 2024-05-28 04:54:05 +00:00
lcnr 4d5a9bcb86 change selection test to run-pass 2024-05-28 04:44:45 +00:00
bors 71213fd607 Auto merge of #125539 - matthiaskrgr:cräsh, r=jieyouxu
crashes: increment the number of tracked ones

r? `@jieyouxu`
2024-05-28 00:28:52 +00:00
Nicholas Nethercote cf0c2c7333 Convert proc_macro_back_compat lint to an unconditional error.
We still check for the `rental`/`allsorts-rental` crates. But now if
they are detected we just emit a fatal error, instead of emitting a
warning and providing alternative behaviour.

The original "hack" implementing alternative behaviour was added
in #73345.

The lint was added in #83127.

The tracking issue is #83125.

The direct motivation for the change is that providing the alternative
behaviour is interfering with #125174 and follow-on work.
2024-05-28 08:15:15 +10:00
Urgau c7d300442f non_local_defs: point the parent item when appropriate 2024-05-27 23:59:18 +02:00
Urgau 98273ec612 non_local_defs: point to Self and Trait to give more context 2024-05-27 23:59:18 +02:00
Urgau b71952904d non_local_defs: suggest removing leading ref/ptr to make the impl local 2024-05-27 23:59:18 +02:00
Urgau ab23fd8dea non_local_defs: improve main without a trait note 2024-05-27 23:59:18 +02:00
Urgau d3dfe14b53 non_local_defs: be more precise about what needs to be moved 2024-05-27 23:59:18 +02:00
Urgau 402580bcd5 non_local_defs: improve exception note for impl and macro_rules!
- Remove wrong exception text for non-local macro_rules!
 - Simplify anonymous const exception note
2024-05-27 23:59:18 +02:00
Urgau 22095fbd8d non_local_defs: use labels to indicate what may need to be moved 2024-05-27 23:58:55 +02:00
Urgau 26b873d030 non_local_defs: use span of the impl def and not the impl block 2024-05-27 23:58:55 +02:00
Urgau de1c122950 non_local_defs: improve some notes around trait, bounds, consts
- Restrict const-anon exception diag to relevant places
 - Invoke bounds (and type-inference) in non_local_defs
 - Specialize diagnostic for impl without Trait
2024-05-27 23:58:55 +02:00
Urgau 06c6a2d9d6 non_local_defs: switch to more friendly primary message 2024-05-27 23:58:55 +02:00
Matthias Krüger bae945201f remove fixed crashes, add fixed crashes to tests, add new cashed found in the meantime 2024-05-27 20:41:09 +02:00
bors b0f8618938 Auto merge of #125413 - lcnr:ambig-drop-region-constraints, r=compiler-errors
drop region constraints for ambiguous goals

See the comment in `compute_external_query_constraints`. While the underlying issue is preexisting, this fixes a bug introduced by #125343.

It slightly weakens the leak chec, even if we didn't have any test which was affected. I want to write such a test before merging this PR.

r? `@compiler-errors`
2024-05-27 15:28:51 +00:00
bors fec98b3bbc Auto merge of #125468 - BoxyUwU:remove_defid_from_regionparam, r=compiler-errors
Remove `DefId` from `EarlyParamRegion`

Currently we represent usages of `Region` parameters via the `ReEarlyParam` or `ReLateParam` variants. The `ReEarlyParam` is effectively equivalent to `TyKind::Param` and `ConstKind::Param` (i.e. it stores a `Symbol` and a `u32` index) however it also stores a `DefId` for the definition of the lifetime parameter.

This was used in roughly two places:
- Borrowck diagnostics instead of threading the appropriate `body_id` down to relevant locations. Interestingly there were already some places that had to pass down a `DefId` manually.
- Some opaque type checking logic was using the `DefId` field to track captured lifetimes

I've split this PR up into a commit for generate rote changes to diagnostics code to pass around a `DefId` manually everywhere, and another commit for the opaque type related changes which likely require more careful review as they might change the semantics of lints/errors.

Instead of manually passing the `DefId` around everywhere I previously tried to bundle it in with `TypeErrCtxt` but ran into issues with some call sites of `infcx.err_ctxt` being unable to provide a `DefId`, particularly places involved with trait solving and normalization. It might be worth investigating adding some new wrapper type to pass this around everywhere but I think this might be acceptable for now.

This pr also has the effect of reducing the size of `EarlyParamRegion` from 16 bytes -> 8 bytes. I wouldn't expect this to have any direct performance improvement however, other variants of `RegionKind` over `8` bytes are all because they contain a `BoundRegionKind` which is, as far as I know, mostly there for diagnostics. If we're ever able to remove this it would shrink the `RegionKind` type from `24` bytes to `12` (and with clever bit packing we might be able to get it to `8` bytes). I am curious what the performance impact would be of removing interning of `Region`'s if we ever manage to shrink `RegionKind` that much.

Sidenote: by removing the `DefId` the `Debug` output for `Region` has gotten significantly nicer. As an example see this opaque type debug print before vs after this PR:
`Opaque(DefId(0:13 ~ impl_trait_captures[aeb9]::foo::{opaque#0}), [DefId(0:9 ~ impl_trait_captures[aeb9]::foo::'a)_'a/#0, T, DefId(0:9 ~ impl_trait_captures[aeb9]::foo::'a)_'a/#0])`
`Opaque(DefId(0:13 ~ impl_trait_captures[aeb9]::foo::{opaque#0}), ['a/#0, T, 'a/#0])`

r? `@compiler-errors` (I would like someone who understands the opaque type setup to atleast review the type system commit, but the rest is likely reviewable by anyone)
2024-05-27 06:36:57 +00:00
Jubilee b65b2b6ced
Rollup merge of #125469 - compiler-errors:dont-skip-inner-const-body, r=cjgillot
Don't skip out of inner const when looking for body for suggestion

Self-explanatory title, I'll point out the important logic in an inline comment.

Fixes #125370
2024-05-26 15:28:27 -07:00
Jubilee 09e75921f3
Rollup merge of #125466 - compiler-errors:dont-probe-for-ambig-in-sugg, r=jieyouxu
Don't continue probing for method if in suggestion and autoderef hits ambiguity

The title is somewhat self-explanatory. When we hit ambiguity in method autoderef steps, we previously would continue to probe for methods if we were giving a suggestion. This seems useless, and causes an ICE when we are not able to unify the receiver later on in confirmation.

Fixes #125432
2024-05-26 15:28:27 -07:00
Jubilee 5860d43af3
Rollup merge of #125046 - bjorn3:no_mutable_static_linkage, r=cjgillot
Only allow immutable statics with #[linkage]
2024-05-26 15:28:26 -07:00
Jubilee 866630d004
Rollup merge of #124048 - veera-sivarajan:bugfix-123773-c23-variadics, r=compiler-errors
Support C23's Variadics Without a Named Parameter

Fixes #123773

This PR removes the static check that disallowed extern functions
with ellipsis (varargs) as the only parameter since this is now
valid in C23.

This will not break any existing code as mentioned in the proposal
document: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2975.pdf.

Also, adds a doc comment for `check_decl_cvariadic_pos()` and
fixes the name of the function (`varadic` -> `variadic`).
2024-05-26 15:28:26 -07:00
Matthias Krüger 5fef6c511d
Rollup merge of #125508 - scottmcm:fix-125506, r=Nilstrieb
Stop SRoA'ing `DynMetadata` in MIR

Fixes #125506
2024-05-26 13:43:07 +02:00
bors 5fe5543502 Auto merge of #124661 - RalfJung:only-structural-consts-in-patterns, r=pnkfelix
Turn remaining non-structural-const-in-pattern lints into hard errors

This completes the implementation of https://github.com/rust-lang/rust/issues/120362 by turning our remaining future-compat lints into hard errors: indirect_structural_match and pointer_structural_match.

They have been future-compat lints for a while (indirect_structural_match for many years, pointer_structural_match since Rust 1.75 (released Dec 28, 2023)), and have shown up in dependency breakage reports since Rust 1.78 (just released on May 2, 2024). I don't expect a lot of code will still depend on them, but we will of course do a crater run.

A lot of cleanup is now possible in const_to_pat, but that is deferred to a later PR.

Fixes https://github.com/rust-lang/rust/issues/70861
2024-05-26 07:55:47 +00:00
bors 75e2c5dcd0 Auto merge of #125518 - saethlin:check-arguments-new-in-const, r=joboet
Move the checks for Arguments constructors to inline const

Thanks `@Skgland` for pointing out this opportunity: https://github.com/rust-lang/rust/pull/117804#discussion_r1612964362
2024-05-26 01:10:39 +00:00
Matthias Krüger 1e841638e3
Rollup merge of #124080 - oli-obk:define_opaque_types10, r=compiler-errors
Some unstable changes to where opaque types get defined

None of these can be reached from stable afaict.

r? ``@compiler-errors``

cc https://github.com/rust-lang/rust/issues/116652
2024-05-25 22:15:17 +02:00
Scott McMurray d7248d7b71 Stop SRoA'ing DynMetadata in MIR 2024-05-25 00:44:47 -07:00
joboet 6df8d0dd4e
fix UI test 2024-05-25 09:37:08 +02:00
bors 21e6de7eb6 Auto merge of #124187 - compiler-errors:self-ctor, r=petrochenkov
Warn (or error) when `Self` ctor from outer item is referenced in inner nested item

This implements a warning `SELF_CONSTRUCTOR_FROM_OUTER_ITEM` when a self constructor from an outer impl is referenced in an inner nested item. This is a proper fix mentioned https://github.com/rust-lang/rust/pull/117246#discussion_r1374648388.

This warning is additionally bumped to a hard error when the self type references generic parameters, since it's almost always going to ICE, and is basically *never* correct to do.

This also reverts part of https://github.com/rust-lang/rust/pull/117246, since I believe this is the proper fix and we shouldn't need the helper functions (`opt_param_at`/`opt_type_param`) any longer, since they shouldn't really ever be used in cases where we don't have this problem.
2024-05-25 01:17:55 +00:00
Ben Kimock 9763222f59 Move the checks for Arguments constructors to inline const 2024-05-24 21:09:15 -04:00
Matthias Krüger 104e1a4bf2
Rollup merge of #125501 - compiler-errors:opaque-opaque-anon-ct, r=BoxyUwU
Resolve anon const's parent predicates to direct parent instead of opaque's parent

When an anon const is inside of an opaque, #99801 added a hack to resolve the anon const's parent predicates *not* to the opaque's predicates, but to the opaque's *parent's* predicates. This is insufficient when considering nested opaques.

This means that the `predicates_of` an anon const might reference duplicated lifetimes (installed by `compute_bidirectional_outlives_predicates`) when computing known outlives in MIR borrowck, leading to these ICEs:
Fixes #121574
Fixes #118403

~~Instead, we should be using the `OpaqueTypeOrigin` to acquire the owner item (fn/type alias/etc) of the opaque, whose predicates we're fine to mention.~~

~~I think it's a bit sketchy that we're doing this at all, tbh; I think it *should* be fine for the anon const to inherit the predicates of the opaque it's located inside. However, that would also mean that we need to make sure the `generics_of` that anon const line up in the same way.~~

~~None of this is important to solve right now; I just want to fix these ICEs so we can land #125468, which accidentally fixes these issues in a different and unrelated way.~~

edit: We don't need this special case anyways because we install the right parent item in `generics_of` anyways:
213ad10c8f/compiler/rustc_hir_analysis/src/collect/generics_of.rs (L150)

r? `@BoxyUwU`
2024-05-24 23:01:11 +02:00
Matthias Krüger fafe13aea4
Rollup merge of #125467 - compiler-errors:binop-in-bool-expectation, r=estebank
Only suppress binop error in favor of semicolon suggestion if we're in an assignment statement

Similar to #123722, we are currently too aggressive when delaying a binop error with the expectation that we'll emit another error elsewhere. This adjusts that heuristic to be more accurate, at the cost of some possibly poorer suggestions.

Fixes #125458
2024-05-24 23:01:09 +02:00
lcnr 24b5466892 drop region constraints for ambiguous goals 2024-05-24 20:32:35 +00:00
Michael Goulet de517b79bc Actually just remove the special case altogether 2024-05-24 13:16:06 -04:00
Boxy fe2d7794ca Remove DefId from EarlyParamRegion (tedium/diagnostics) 2024-05-24 18:06:53 +01:00
Michael Baikov b70fb4159b And more general error 2024-05-24 11:20:33 -04:00
Oli Scherer 526090b901 Add regression tests 2024-05-24 14:01:49 +00:00
surechen 09c8e39adb A small diagnostic improvement for dropping_copy_types
fixes #125189
2024-05-24 19:31:57 +08:00
Michael Baikov d6e4fe569c A custom error message for lending iterators 2024-05-24 07:23:30 -04:00
bors 7c547894c7 Auto merge of #125457 - fmease:gacs-diag-infer-plac-missing-ty, r=compiler-errors
Properly deal with missing/placeholder types inside GACs

Fixes #124833.

r? oli-obk (#123130)
2024-05-24 06:45:40 +00:00
Michael Goulet c58b7c9c81 Don't skip inner const when looking for body for suggestion 2024-05-23 19:49:48 -04:00
Michael Goulet 4bc41b91d7 Don't continue probing for method if in suggestion and autoderef hits ambiguity 2024-05-23 19:42:10 -04:00
Michael Goulet a02aba7c54 Only suppress binop error in favor of semicolon suggestion if we're in an assignment statement 2024-05-23 19:22:55 -04:00
León Orell Valerian Liehr 39d9b840bb
Handle trait/impl GAC mismatches when inferring missing/placeholder types 2024-05-24 00:42:32 +02:00
León Orell Valerian Liehr 24afa42a90
Properly deal with missing/placeholder types inside GACs 2024-05-24 00:36:32 +02:00
Guillaume Gomez 56427d3372
Rollup merge of #125412 - Urgau:check-cfg-less-build-rs, r=wesleywiser
Don't suggest adding the unexpected cfgs to the build-script it-self

This PR adds a check to avoid suggesting to add the unexpected cfgs inside the build-script when building the build-script it-self, as it won't have any effect, since build-scripts applies to their descended target.

Fixes #125368
2024-05-23 23:39:28 +02:00
León Orell Valerian Liehr c99b3f24c2
Rollup merge of #122382 - mu001999:dead_code/enhance, r=petrochenkov
Detect unused structs which implement private traits

Fixes #122361
2024-05-23 20:09:07 +02:00
Oli Scherer 4387eea7f7 Support constraining opaque types while trait upcasting with binders 2024-05-23 16:02:24 +00:00
Oli Scherer 7f292f41a0 Allow defining opaque types during trait object upcasting.
No stable code is affected, as this requires the `trait_upcasting` feature gate.
2024-05-23 16:02:20 +00:00
Oli Scherer 29a630eb72 When checking whether an impl applies, constrain hidden types of opaque types.
We already handle this case this way on the coherence side, and it matches the new solver's behaviour. While there is some breakage around type-alias-impl-trait (see new "type annotations needed" in tests/ui/type-alias-impl-trait/issue-84660-unsoundness.rs), no stable code breaks, and no new stable code is accepted.
2024-05-23 15:52:10 +00:00
Oli Scherer dc8d1bc373 Add more tests 2024-05-23 15:48:06 +00:00
bors 9c8a58fdb8 Auto merge of #116123 - joboet:rewrite_native_tls, r=m-ou-se
Rewrite native thread-local storage

(part of #110897)

The current native thread-local storage implementation has become quite messy, uses indescriptive names and unnecessarily adds code to the macro expansion. This PR tries to fix that by using a new implementation that also allows more layout optimizations and potentially increases performance by eliminating unnecessary TLS accesses.

This does not change the recursive initialization behaviour I described in [this comment](https://github.com/rust-lang/rust/issues/110897#issuecomment-1525705682), so it should be a library-only change. Changing that behaviour should be quite easy now, however.

r? `@m-ou-se`
`@rustbot` label +T-libs
2024-05-23 14:53:41 +00:00
Matthias Krüger e713b2a00c
Rollup merge of #125416 - compiler-errors:param-env-missing-copy, r=lcnr
Use correct param-env in `MissingCopyImplementations`

We shouldn't assume the param-env is empty for this lint, since although we check the struct has no parameters, there still may be trivial where-clauses.

fixes #125394
2024-05-23 14:09:25 +02:00
Matthias Krüger 337987bf63
Rollup merge of #125210 - fmease:fix-up-some-diags, r=davidtwco
Cleanup: Fix up some diagnostics

Several diagnostics contained their error code inside their primary message which is no bueno.
This PR moves them out of the message and turns them into structured error codes.

Also fixes another occurrence of `->` after a selector in a Fluent message which is not correct. I've fixed two other instances of this issue in #104345 (2022) but didn't update all instances as I've noted here: https://github.com/rust-lang/rust/pull/104345#issuecomment-1312705977 (“the future is now!”).
2024-05-23 14:09:24 +02:00
Matthias Krüger eda4a35f36
Rollup merge of #124976 - petrochenkov:usedcrates, r=oli-obk
rustc: Use `tcx.used_crates(())` more

And explain when it should be used.

Addresses comments from https://github.com/rust-lang/rust/pull/121167.
2024-05-23 14:09:23 +02:00
Matthias Krüger eb6b35b5bc
Rollup merge of #124516 - oli-obk:taint_const_eval, r=RalfJung
Allow monomorphization time const eval failures if the cause is a type layout issue

r? `@RalfJung`

fixes  #124348
2024-05-23 14:09:23 +02:00
Matthias Krüger abcf400a28
Rollup merge of #124297 - oli-obk:define_opaque_types13, r=jackh726
Allow coercing functions whose signature differs in opaque types in their defining scope into a shared function pointer type

r? `@compiler-errors`

This accepts more code on stable. It is now possible to have match arms return a function item `foo` and a different function item `bar` in another, and that will constrain OpaqueTypeInDefiningScope to have the hidden type ConcreteType and make the type of the match arms a function pointer that matches the signature. So the following function will now compile, but on master it errors with a type mismatch on the second match arm

```rust
fn foo<T>(t: T) -> T {
    t
}

fn bar<T>(t: T) -> T {
    t
}

fn k() -> impl Sized {
    fn bind<T, F: FnOnce(T) -> T>(_: T, f: F) -> F {
        f
    }
    let x = match true {
        true => {
            let f = foo;
            bind(k(), f)
        }
        false => bar::<()>,
    };
    todo!()
}
```

cc https://github.com/rust-lang/rust/issues/116652

This is very similar to https://github.com/rust-lang/rust/pull/123794, and with the same rationale:

> this is for consistency with `-Znext-solver`. the new solver does not have the concept of "non-defining use of opaque" right now and we would like to ideally keep it that way. Moving to `DefineOpaqueTypes::Yes` in more cases removes subtlety from the type system. Right now we have to be careful when relating `Opaque` with another type as the behavior changes depending on whether we later use the `Opaque` or its hidden type directly (even though they are equal), if that later use is with `DefineOpaqueTypes::No`*
2024-05-23 14:09:22 +02:00
joboet 60bf1ab466
delete UI tests that only check internal implementation details of thread-locals 2024-05-23 13:44:56 +02:00
Oli Scherer 4cf34cb752 Allow const eval failures if the cause is a type layout issue 2024-05-23 10:51:52 +00:00
Oli Scherer 301c8decce Add regression tests 2024-05-23 10:48:39 +00:00
bors 39d2f2affd Auto merge of #125436 - matthiaskrgr:rollup-uijo2ga, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #122665 (Add some tests for public-private dependencies.)
 - #123623 (Fix OutsideLoop's error suggestion: adding label `'block` for `if` block.)
 - #125054 (Handle `ReVar` in `note_and_explain_region`)
 - #125156 (Expand `for_loops_over_fallibles` lint to lint on fallibles behind references.)
 - #125222 (Migrate `run-make/issue-46239` to `rmake`)
 - #125316 (Tweak `Spacing` use)
 - #125392 (Wrap Context.ext in AssertUnwindSafe)
 - #125417 (self-contained linker: retry linking without `-fuse-ld=lld` on CCs that don't support it)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-23 06:14:03 +00:00
Matthias Krüger 5126d4b87b
Rollup merge of #125392 - workingjubilee:unwind-a-problem-in-context, r=Amanieu
Wrap Context.ext in AssertUnwindSafe

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

Alternative to https://github.com/rust-lang/rust/pull/125377

Relevant to https://github.com/rust-lang/rust/issues/123392

I believe this approach is justifiable due to the fact that this function is unstable API and we have been considering trying to dispose of the notion of "unwind safety". Making a more long-term decision should be considered carefully as part of stabilizing `fn ext`, if ever.

r? `@Amanieu`
2024-05-23 07:41:19 +02:00
Matthias Krüger 4af1c31fcf
Rollup merge of #125156 - zachs18:for_loops_over_fallibles_behind_refs, r=Nilstrieb
Expand `for_loops_over_fallibles` lint to lint on fallibles behind references.

Extends the scope of the (warn-by-default) lint `for_loops_over_fallibles` from just `for _ in x` where `x: Option<_>/Result<_, _>` to also cover `x: &(mut) Option<_>/Result<_>`

```rs
fn main() {
    // Current lints
    for _ in Some(42) {}
    for _ in Ok::<_, i32>(42) {}

    // New lints
    for _ in &Some(42) {}
    for _ in &mut Some(42) {}
    for _ in &Ok::<_, i32>(42) {}
    for _ in &mut Ok::<_, i32>(42) {}

    // Should not lint
    for _ in Some(42).into_iter() {}
    for _ in Some(42).iter() {}
    for _ in Some(42).iter_mut() {}
    for _ in Ok::<_, i32>(42).into_iter() {}
    for _ in Ok::<_, i32>(42).iter() {}
    for _ in Ok::<_, i32>(42).iter_mut() {}
}
```

<details><summary><code>cargo build</code> diff</summary>

```diff
diff --git a/old.out b/new.out
index 84215aa..ca195a7 100644
--- a/old.out
+++ b/new.out
`@@` -1,33 +1,93 `@@`
 warning: for loop over an `Option`. This is more readably written as an `if let` statement
  --> src/main.rs:3:14
   |
 3 |     for _ in Some(42) {}
   |              ^^^^^^^^
   |
   = note: `#[warn(for_loops_over_fallibles)]` on by default
 help: to check pattern in a loop use `while let`
   |
 3 |     while let Some(_) = Some(42) {}
   |     ~~~~~~~~~~~~~~~ ~~~
 help: consider using `if let` to clear intent
   |
 3 |     if let Some(_) = Some(42) {}
   |     ~~~~~~~~~~~~ ~~~

 warning: for loop over a `Result`. This is more readably written as an `if let` statement
  --> src/main.rs:4:14
   |
 4 |     for _ in Ok::<_, i32>(42) {}
   |              ^^^^^^^^^^^^^^^^
   |
 help: to check pattern in a loop use `while let`
   |
 4 |     while let Ok(_) = Ok::<_, i32>(42) {}
   |     ~~~~~~~~~~~~~ ~~~
 help: consider using `if let` to clear intent
   |
 4 |     if let Ok(_) = Ok::<_, i32>(42) {}
   |     ~~~~~~~~~~ ~~~

-warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 2 warnings
-    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.04s
+warning: for loop over a `&Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:7:14
+  |
+7 |     for _ in &Some(42) {}
+  |              ^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+7 |     while let Some(_) = &Some(42) {}
+  |     ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+7 |     if let Some(_) = &Some(42) {}
+  |     ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:8:14
+  |
+8 |     for _ in &mut Some(42) {}
+  |              ^^^^^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+8 |     while let Some(_) = &mut Some(42) {}
+  |     ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+8 |     if let Some(_) = &mut Some(42) {}
+  |     ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&Result`. This is more readably written as an `if let` statement
+ --> src/main.rs:9:14
+  |
+9 |     for _ in &Ok::<_, i32>(42) {}
+  |              ^^^^^^^^^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+9 |     while let Ok(_) = &Ok::<_, i32>(42) {}
+  |     ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+9 |     if let Ok(_) = &Ok::<_, i32>(42) {}
+  |     ~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Result`. This is more readably written as an `if let` statement
+  --> src/main.rs:10:14
+   |
+10 |     for _ in &mut Ok::<_, i32>(42) {}
+   |              ^^^^^^^^^^^^^^^^^^^^^
+   |
+help: to check pattern in a loop use `while let`
+   |
+10 |     while let Ok(_) = &mut Ok::<_, i32>(42) {}
+   |     ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+   |
+10 |     if let Ok(_) = &mut Ok::<_, i32>(42) {}
+   |     ~~~~~~~~~~ ~~~
+
+warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 6 warnings
+    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s

```

</details>

-----

Question:

* ~~Currently, the article `an` is used for `&Option`, and `&mut Option` in the lint diagnostic, since that's what `Option` uses. Is this okay or should it be changed? (likewise, `a` is used for `&Result` and `&mut Result`)~~ The article `a` is used for `&Option`, `&mut Option`, `&Result`, `&mut Result` and (as before) `Result`. Only `Option` uses `an` (as before).

`@rustbot` label +A-lint
2024-05-23 07:41:17 +02:00
Matthias Krüger 72fd85c617
Rollup merge of #125054 - nnethercote:fix-124973, r=compiler-errors
Handle `ReVar` in `note_and_explain_region`

PR #124918 made this path abort. The added test, from fuzzing, identified that it is reachable.

r? `@lcnr`
2024-05-23 07:41:17 +02:00
Matthias Krüger 96134e15f6
Rollup merge of #123623 - surechen:fix_123261, r=estebank
Fix OutsideLoop's error suggestion: adding label `'block` for `if` block.

For OutsideLoop we should not suggest add `'block` label in `if` block, or we wiil get another err: block label not supported here.

fixes #123261
2024-05-23 07:41:16 +02:00
Matthias Krüger 5ee8267241
Rollup merge of #122665 - ehuss:pub-priv-tests, r=davidtwco
Add some tests for public-private dependencies.

This adds some tests to show more scenarios for the `exported_private_dependencies` lint. Several of these illustrate that the lint is not working as expected, and I have annotated those places with `FIXME`.

Note also that this includes some diamond dependency structures which compiletest doesn't exactly support. However, I don't think it should be a problem, it just results in the common dependency being built twice.
2024-05-23 07:41:16 +02:00
bors 5293c6adb7 Auto merge of #125359 - RalfJung:interpret-overflowing-ops, r=oli-obk
interpret: make overflowing binops just normal binops

Follow-up to https://github.com/rust-lang/rust/pull/125173 (Cc `@scottmcm)`
2024-05-23 04:03:14 +00:00
Nicholas Nethercote 5f4424bfaf Handle ReVar in note_and_explain_region.
PR #124918 made this path abort. The added test, from fuzzing,
identified that it is reachable.
2024-05-23 12:16:49 +10:00
Gurinder Singh 273a78b05b Do not suggest unresolvable builder methods 2024-05-23 07:23:59 +05:30
r0cky 96968350e1 Detect unused structs which implement private traits 2024-05-23 09:07:59 +08:00
bors 9cdfe285ca Auto merge of #125423 - fmease:rollup-ne4l9y4, r=fmease
Rollup of 7 pull requests

Successful merges:

 - #125043 (reference type safety invariant docs: clarification)
 - #125306 (Force the inner coroutine of an async closure to `move` if the outer closure is `move` and `FnOnce`)
 - #125355 (Use Backtrace::force_capture instead of Backtrace::capture in rustc_log)
 - #125382 (rustdoc: rename `issue-\d+.rs` tests to have meaningful names (part 7))
 - #125391 (Minor serialize/span tweaks)
 - #125395 (Remove unnecessary `.md` from the documentation sidebar)
 - #125399 (Stop using `to_hir_binop` in codegen)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-22 21:51:26 +00:00
León Orell Valerian Liehr d2f0df7713
Rollup merge of #125306 - compiler-errors:closure-incongruency, r=oli-obk
Force the inner coroutine of an async closure to `move` if the outer closure is `move` and `FnOnce`

See the detailed comment in `upvar.rs`.

Fixes #124867.
Fixes #124487.

r? oli-obk
2024-05-22 23:41:11 +02:00
Eric Huss 07b7cd62c7 Add some tests for public-private dependencies. 2024-05-22 13:47:15 -07:00
León Orell Valerian Liehr ae49dbe707
Cleanup: Fix up some diagnostics 2024-05-22 22:40:34 +02:00
Urgau 1c7859e117 Don't suggest adding the unexpected cfgs the build-script it-self 2024-05-22 20:58:57 +02:00
León Orell Valerian Liehr 44c7a2dbff
Rollup merge of #125259 - compiler-errors:fn-mut-as-a-treat, r=oli-obk
An async closure may implement `FnMut`/`Fn` if it has no self-borrows

There's no reason that async closures may not implement `FnMut` or `Fn` if they don't actually borrow anything with the closure's env lifetime. Specifically, #123660 made it so that we don't always need to borrow captures from the closure's env.

See the doc comment on `should_reborrow_from_env_of_parent_coroutine_closure`:

c00957a3e2/compiler/rustc_hir_typeck/src/upvar.rs (L1777-L1823)

If there are no such borrows, then we are free to implement `FnMut` and `Fn` as permitted by our closure's inferred `ClosureKind`.

As far as I can tell, this change makes `async || {}` work in precisely the set of places they used to work before #120361.
Fixes #125247.

r? oli-obk
2024-05-22 19:04:45 +02:00
León Orell Valerian Liehr 5b485f04de
Rollup merge of #125049 - dtolnay:castbrace, r=compiler-errors
Disallow cast with trailing braced macro in let-else

This fixes an edge case I noticed while porting #118880 and #119062 to syn.

Previously, rustc incorrectly accepted code such as:

```rust
let foo = &std::ptr::null as &'static dyn std::ops::Fn() -> *const primitive! {
    8
} else {
    return;
};
```

even though a right curl brace `}` directly before `else` in a `let...else` statement is not supposed to be valid syntax.
2024-05-22 19:04:44 +02:00
León Orell Valerian Liehr b3604de1df
Rollup merge of #125015 - fmease:pat-tys-proh-gen-args-on-ct-params, r=spastorino
Pattern types: Prohibit generic args on const params

Addresses https://github.com/rust-lang/rust/pull/123689/files#r1562676629.

NB: Technically speaking, *not* prohibiting generics args on const params is not a bug as `pattern_types` is an *internal* feature and as such any uncaught misuses of it are considered to be the fault of the user. However, permitting this makes me slightly uncomfortable esp. since we might want to make pattern types available to the public at some point and I don't want this oversight to be able to slip into the language (for comparison, ICEs triggered by the use of internal features are like super fine).

Furthermore, this is an ad hoc fix. A more general fix would be changing the representation of the pattern part of pattern types in such a way that it can reuse preexisting lowering routines for exprs / anon consts. See also this [Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/pattern.20type.20HIR.20nodes/near/432410768) and #124650.

Also note that we currently don't properly typeck the pattern of pat tys. This however is out of scope for this PR.

cc ``@oli-obk``
r? ``@spastorino`` as discussed
2024-05-22 19:04:44 +02:00
Michael Goulet 8369dbba43 Use correct param-env in MissingCopyImplementations 2024-05-22 12:46:08 -04:00
Vadim Petrochenkov 711338bd9f rustc: Use tcx.used_crates(()) more
And explain when it should be used.
2024-05-22 18:02:51 +03:00
bors 5d328a1f62 Auto merge of #117329 - RalfJung:offset-by-zero, r=oli-obk,scottmcm
offset: allow zero-byte offset on arbitrary pointers

As per prior `@rust-lang/opsem` [discussion](https://github.com/rust-lang/opsem-team/issues/10) and [FCP](https://github.com/rust-lang/unsafe-code-guidelines/issues/472#issuecomment-1793409130):

- Zero-sized reads and writes are allowed on all sufficiently aligned pointers, including the null pointer
- Inbounds-offset-by-zero is allowed on all pointers, including the null pointer
- `offset_from` on two pointers derived from the same allocation is always allowed when they have the same address

This removes surprising UB (in particular, even C++ allows "nullptr + 0", which we currently disallow), and it brings us one step closer to an important theoretical property for our semantics ("provenance monotonicity": if operations are valid on bytes without provenance, then adding provenance can't make them invalid).

The minimum LLVM we require (v17) includes https://reviews.llvm.org/D154051, so we can finally implement this.

The `offset_from` change is needed to maintain the equivalence with `offset`: if `let ptr2 = ptr1.offset(N)` is well-defined, then `ptr2.offset_from(ptr1)` should be well-defined and return N. Now consider the case where N is 0 and `ptr1` dangles: we want to still allow offset_from here.

I think we should change offset_from further, but that's a separate discussion.

Fixes https://github.com/rust-lang/rust/issues/65108
[Tracking issue](https://github.com/rust-lang/rust/issues/117945) | [T-lang summary](https://github.com/rust-lang/rust/pull/117329#issuecomment-1951981106)

Cc `@nikic`
2024-05-22 13:04:14 +00:00
surechen 8fde7e3b64 For OutsideLoop we should not suggest add 'block label in if block, or we wiil get another err: block label not supported here.
fixes #123261
2024-05-22 19:47:32 +08:00
bors f0038a7c8f Auto merge of #124227 - compiler-errors:hack-check-method-res, r=estebank
Make sure that the method resolution matches in `note_source_of_type_mismatch_constraint`

`note_source_of_type_mismatch_constraint` is a pile of hacks that I implemented to cover up another pile of hacks.

It does a bunch of re-confirming methods, but it wasn't previously checking that the methods it was looking (back) up were equal to the methods we previously had. This PR adds those checks.

Fixes #118185
2024-05-22 10:57:59 +00:00
bors b54dd08a84 Auto merge of #125326 - weiznich:move/do_not_recommend_to_diganostic_namespace, r=compiler-errors
Move `#[do_not_recommend]` to the `#[diagnostic]` namespace

This commit moves the `#[do_not_recommend]` attribute to the `#[diagnostic]` namespace. It still requires
`#![feature(do_not_recommend)]` to work.

r? `@compiler-errors`
2024-05-22 04:14:08 +00:00
Jubilee Young 3a21fb5cec Wrap Context.ext in AssertUnwindSafe 2024-05-21 19:05:37 -07:00
bors 791adf759c Auto merge of #124417 - Xiretza:translate-early-lints, r=fmease
Make early lints translatable

<del>Requires https://github.com/projectfluent/fluent-rs/pull/353.</del> 5134a04eaa

r? diagnostics
2024-05-21 21:36:09 +00:00
Xiretza c4f6502c6d Fix typo in deprecation lint message 2024-05-21 20:16:39 +00:00
Xiretza 8004e6a379 Make early lints translatable 2024-05-21 20:16:39 +00:00
Xiretza 2482f3c17c Convert unexpected_cfg_{name,value} to struct diagnostics 2024-05-21 20:16:39 +00:00
Matthias Krüger 1b57ef3207
Rollup merge of #125310 - workingjubilee:muck-out-the-test-stables, r=Nilstrieb
Move ~100 tests from tests/ui to subdirs

new dirs for some, the rest in old
sweep tests up before they turn cold
to stop our code from growing mold
2024-05-21 20:28:48 +02:00
Matthias Krüger bfa98d318f
Rollup merge of #125276 - dev-ardi:no-main-diag, r=fmease
Fix parsing of erroneously placed semicolons

This closes https://github.com/rust-lang/rust/issues/124935, is a continuation of https://github.com/rust-lang/rust/pull/125245 after rebasing https://github.com/rust-lang/rust/pull/125117.

Thanks ```@gurry``` for your code and sorry for making it confusing :P

r? fmease
2024-05-21 20:28:47 +02:00
Matthias Krüger 6009cb776a
Rollup merge of #123122 - surechen:fix_122714, r=fmease
Fix incorrect suggestion for undeclared hrtb lifetimes in where clauses.

For poly-trait-ref like `for<'a> Trait<T>`   in  `T: for<'a> Trait<T> + 'b { }`.
We should merge the hrtb lifetimes: existed `for<'a>` and suggestion `for<'b>` or will get err: [E0316] nested quantification of lifetimes

fixes #122714
2024-05-21 20:28:46 +02:00
bors 506512391b Auto merge of #124676 - djkoloski:relax_multiple_sanitizers, r=cuviper,rcvalle
Relax restrictions on multiple sanitizers

Most combinations of LLVM sanitizers are legal-enough to enable simultaneously. This change will allow simultaneously enabling ASAN and shadow call stacks on supported platforms.

I used this python script to generate the mutually-exclusive sanitizer combinations:

```python
#!/usr/bin/python3

import subprocess

flags = [
    ["-fsanitize=address"],
    ["-fsanitize=leak"],
    ["-fsanitize=memory"],
    ["-fsanitize=thread"],
    ["-fsanitize=hwaddress"],
    ["-fsanitize=cfi", "-flto", "-fvisibility=hidden"],
    ["-fsanitize=memtag", "--target=aarch64-linux-android", "-march=armv8a+memtag"],
    ["-fsanitize=shadow-call-stack"],
    ["-fsanitize=kcfi", "-flto", "-fvisibility=hidden"],
    ["-fsanitize=kernel-address"],
    ["-fsanitize=safe-stack"],
    ["-fsanitize=dataflow"],
]

for i in range(len(flags)):
    for j in range(i):
        command = ["clang++"] + flags[i] + flags[j] + ["-o", "main.o", "-c", "main.cpp"]
        completed = subprocess.run(command, stderr=subprocess.DEVNULL)
        if completed.returncode != 0:
            first = flags[i][0][11:].replace('-', '').upper()
            second = flags[j][0][11:].replace('-', '').upper()
            print(f"(SanitizerSet::{first}, SanitizerSet::{second}),")
```
2024-05-21 15:35:29 +00:00
Ralf Jung c0b4b454c3 interpret: make overflowing binops just normal binops 2024-05-21 14:50:09 +02:00
bors 6715446db6 Auto merge of #125358 - matthiaskrgr:rollup-mx841tg, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #124570 (Miscellaneous cleanups)
 - #124772 (Refactor documentation for Apple targets)
 - #125011 (Add opt-for-size core lib feature flag)
 - #125218 (Migrate `run-make/no-intermediate-extras` to new `rmake.rs`)
 - #125225 (Use functions from `crt_externs.h` on iOS/tvOS/watchOS/visionOS)
 - #125266 (compiler: add simd_ctpop intrinsic)
 - #125348 (Small fixes to `std::path::absolute` docs)

Failed merges:

 - #125296 (Fix `unexpected_cfgs` lint on std)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-21 12:50:09 +00:00
Georg Semmler 2cff3e90bc
Move #[do_not_recommend] to the #[diagnostic] namespace
This commit moves the `#[do_not_recommend]` attribute to the
`#[diagnostic]` namespace. It still requires
`#![feature(do_not_recommend)]` to work.
2024-05-21 13:14:41 +02:00
Matthias Krüger fd975f75fa
Rollup merge of #125266 - workingjubilee:stream-plastic-love, r=RalfJung,nikic
compiler: add simd_ctpop intrinsic

Fairly straightforward addition.

cc `@rust-lang/opsem` new (extremely boring) intrinsic
2024-05-21 12:47:06 +02:00
bors e8fbd99128 Auto merge of #124097 - compiler-errors:box-into-iter, r=WaffleLapkin
Add `IntoIterator` for `Box<[T]>` + edition 2024-specific lints

* Adds a similar method probe opt-out mechanism to the `[T;N]: IntoIterator` implementation for edition 2021.
* Adjusts the relevant lints (shadowed `.into_iter()` calls, new source of method ambiguity).
* Adds some tests.
* Took the liberty to rework the logic in the `ARRAY_INTO_ITER` lint, since it was kind of confusing.

Based mostly off of #116607.

ACP: rust-lang/libs-team#263
References #59878
Tracking for Rust 2024: https://github.com/rust-lang/rust/issues/123759

Crater run was done here: https://github.com/rust-lang/rust/pull/116607#issuecomment-1770293013
Consensus afaict was that there is too much breakage, so let's do this in an edition-dependent way much like `[T; N]: IntoIterator`.
2024-05-21 10:13:53 +00:00
bors e875391458 Auto merge of #123812 - compiler-errors:additional-fixes, r=fmease
Follow-up fixes to `report_return_mismatched_types`

Some renames, simplifications, fixes, etc. Follow-ups to #123804. I don't think it totally disentangles this code, but it does remove some of the worst offenders on the "I am so confused" scale (e.g. `get_node_fn_decl`).
2024-05-21 08:06:41 +00:00
Jubilee Young d89500843c Move 100 entries from tests/ui into subdirs
- Move super-fast-paren-parsing test into ui/parser
- Move stmt_expr_attrs test into ui/feature-gates
- Move macro tests into ui/macros
- Move global_asm tests into ui/asm
- Move env tests into ui/process
- Move xcrate tests into ui/cross-crate
- Move unop tests into ui/unop
- Move backtrace tests into ui/backtrace
- Move check-static tests into ui/statics
- Move expr tests into ui/expr
- Move optimization fuel tests into ui/fuel
- Move ffi attribute tests into ui/ffi-attrs
- Move suggestion tests into ui/suggestions
- Move main tests into ui/fn-main
- Move lint tests into ui/lint
- Move repr tests into ui/repr
- Move intrinsics tests into ui/intrinsics
- Move tool lint tests into ui/tool-attributes
- Move return tests into ui/return
- Move pattern tests into ui/patttern
- Move range tests into ui/range
- Move foreign-fn tests into ui/foreign
- Move orphan-check tests into ui/coherence
- Move inference tests into ui/inference
- Reduce ROOT_ENTRY_LIMIT
2024-05-20 19:55:59 -07:00
Michael Goulet a2a6fe7e51 Inline get_node_fn_decl into get_fn_decl, simplify/explain logic in report_return_mismatched_types 2024-05-20 20:16:29 -04:00
Michael Goulet bc6b70f1d1 Adjust the method ambiguity lint too 2024-05-20 19:21:38 -04:00
Michael Goulet a502e7ac1d Implement BOXED_SLICE_INTO_ITER 2024-05-20 19:21:30 -04:00
Michael Goulet c86a4aa5ca Backticks 2024-05-20 19:16:36 -04:00
Matthias Krüger e97103ff6c
Rollup merge of #125308 - lcnr:search-graph-5, r=compiler-errors
track cycle participants per root

The search graph may have multiple roots, e.g. in
```
A :- B
B :- A, C
C :- D
D :- C
```
we first encounter the `A -> B -> A` cycle which causes `A` to be a root. We then later encounter the `C -> D -> C` cycle as a nested goal of `B`. This cycle is completely separate and `C` will get moved to the global cache. This previously caused us to use `[B, D]` as the `cycle_participants` for `C` and `[]` for `A`.

split off from #125167 as I would like to merge this change separately and will rebase that PR on top of this one. There is no test for this issue and I don't quite know how to write one. It is probably worth it to generalize the search graph to enable us to write unit tests for it.

r? `@compiler-errors`
2024-05-21 00:47:02 +02:00
Matthias Krüger 4b26045b92
Rollup merge of #125158 - Nilstrieb:block-indent, r=compiler-errors
hir pretty: fix block indent

before:
```rust
fn main() {
        {
                {
                        ::std::io::_print(format_arguments::new_const(&["Hello, world!\n"]));
                    };
            }
    }
```
after:
```rust
fn main() {
    {
        {
            ::std::io::_print(format_arguments::new_const(&["Hello, world!\n"]));
        };
    }
}
```

AST pretty does the same.
2024-05-21 00:47:02 +02:00
Matthias Krüger e275d2dad6
Rollup merge of #124283 - surechen:fix_123558, r=estebank
Note for E0599 if shadowed bindings has the method.

implement #123558

Use a visitor to find earlier shadowed bingings which has the method.

r? ``@estebank``
2024-05-21 00:47:01 +02:00
Matthias Krüger 8903de31ca
Rollup merge of #124050 - saethlin:less-sysroot-libc, r=ChrisDenton
Remove libc from MSVC targets

``@ChrisDenton`` started working on a project to remove libc from Windows MSVC targets. I'm completing that work here.

The primary change is to cfg out the dependency in `library/`. And then there's a lot of test patching. Happy to separate this more if people want.
2024-05-21 00:47:00 +02:00
lcnr f99c9ffd88 track cycle participants per entry 2024-05-20 20:57:14 +00:00
bors b92758a9ae Auto merge of #125219 - Urgau:check-cfg-cargo-config, r=fmease
Update `unexpected_cfgs` lint for Cargo new `check-cfg` config

This PR updates the diagnostics output of the `unexpected_cfgs` lint for Cargo new `check-cfg` config.

It's a simple and cost-less alternative to the build-script `cargo::rustc-check-cfg` instruction.

```toml
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(foo, values("bar"))'] }
```

This PR also adds a Cargo specific section regarding check-cfg and Cargo inside rustc's book (motivation is described inside the file, but mainly check-cfg is a rustc feature not a Cargo one, Cargo only enabled the feature, it does not own it; T-cargo even considers the `check-cfg` lint config to be an implementation detail).

This PR also updates the links to refer to that sub-page when using Cargo from rustc.

As well as updating the lint doc to refer to the check-cfg docs.

~**Not to be merged before https://github.com/rust-lang/cargo/pull/13913 reaches master!**~ (EDIT: merged in https://github.com/rust-lang/rust/pull/125237)

`@rustbot` label +F-check-cfg
r? `@fmease` *(feel free to roll)*
Fixes https://github.com/rust-lang/rust/issues/124800
cc `@epage` `@weihanglo`
2024-05-20 20:14:09 +00:00
ardi 972633f530 Fix parsing of erroneously placed semicolons 2024-05-20 21:36:20 +02:00
Nilstrieb 7b1527ff5f hir pretty: fix block indent 2024-05-20 20:30:44 +02:00
Matthias Krüger a79737c3f0
Rollup merge of #125314 - jdonszelmann:global-registration-feature-gate, r=pnkfelix
Add an experimental feature gate for global registration

See #125119 for the tracking issue.
2024-05-20 18:13:49 +02:00
Matthias Krüger ba1bb80b6b
Rollup merge of #124917 - cardigan1008:issue-124819, r=pnkfelix
Check whether the next_node is else-less if in get_return_block

Fix #124819
2024-05-20 18:13:47 +02:00
Matthias Krüger 29c603c1fa
Rollup merge of #124682 - estebank:issue-40990, r=pnkfelix
Suggest setting lifetime in borrowck error involving types with elided lifetimes

```
error: lifetime may not live long enough
  --> $DIR/ex3-both-anon-regions-both-are-structs-2.rs:7:5
   |
LL | fn foo(mut x: Ref, y: Ref) {
   |        -----       - has type `Ref<'_, '1>`
   |        |
   |        has type `Ref<'_, '2>`
LL |     x.b = y.b;
   |     ^^^^^^^^^ assignment requires that `'1` must outlive `'2`
   |
help: consider introducing a named lifetime parameter
   |
LL | fn foo<'a>(mut x: Ref<'a, 'a>, y: Ref<'a, 'a>) {
   |       ++++           ++++++++        ++++++++
```

As can be seen above, it currently doesn't try to compare the `ty::Ty` lifetimes that diverged vs the `hir::Ty` to correctly suggest the following

```
help: consider introducing a named lifetime parameter
   |
LL | fn foo<'a>(mut x: Ref<'_, 'a>, y: Ref<'_, 'a>) {
   |       ++++           ++++++++        ++++++++
```

but I believe this to still be an improvement over the status quo.

Fix #40990.
2024-05-20 18:13:46 +02:00
Ben Kimock 39ef149a29 Undo accidental change to tests/ui/sanitizer/thread.rs 2024-05-20 11:13:33 -04:00
Ben Kimock f45a7a291c Fix feature-gates/rustc-private.rs 2024-05-20 11:13:10 -04:00
Ben Kimock 7a906e1af7 Port stdout-during-shutdown 2024-05-20 11:13:10 -04:00
Ben Kimock 70147cd3ab Patch up foreign-fn-linkname.rs 2024-05-20 11:13:10 -04:00
Ben Kimock 281178de42 Add a Windows version of foreign2.rs 2024-05-20 11:13:10 -04:00
Ben Kimock 18b0a07d49 Handle a few more simple tests 2024-05-20 11:13:10 -04:00
Ben Kimock e0632d7cec Add only-unix to sigpipe tests 2024-05-20 11:13:10 -04:00
Ben Kimock 8d3bc55904 Fix up a few more tests 2024-05-20 11:13:10 -04:00
surechen 4ebbb5f048 Fix incorrect suggestion for undeclared hrtb lifetimes in where clauses.
fixes #122714
2024-05-20 20:28:57 +08:00
surechen b092b5d02b Note for E0599 if shadowed bindings has the method.
implement #123558
2024-05-20 18:53:17 +08:00
Urgau ccd3e99a1a Fix quote escaping inside check-cfg value 2024-05-20 11:44:09 +02:00
jdonszelmann 1d9757cd84
add todo test for feature gate 2024-05-20 09:18:49 +02:00
Matthias Krüger ecbd110c7e
Rollup merge of #125302 - workingjubilee:prefer-my-stack-neat, r=compiler-errors
defrost `RUST_MIN_STACK=ice rustc hello.rs`

I didn't think too hard about testing my previous PR rust-lang/rust#122847 which makes our stack overflow handler assist people in discovering the `RUST_MIN_STACK` variable (which apparently is surprisingly useful for Really Big codebases). After it was merged, some useful comments left in a drive-by review led me to discover I had added an ICE. This reworks the code a bit to explain the rationale, remove the ICE that I introduced, and properly test one of the diagnostics.
2024-05-20 08:31:42 +02:00
Matthias Krüger 199d3bf3e4
Rollup merge of #125301 - jwong101:fix-static-coro-suggest, r=compiler-errors
fix suggestion in E0373 for !Unpin coroutines

Coroutines can be prefixed with the `static` keyword to make them
`!Unpin`.
However, given the following function:

```rust

fn check() -> impl Sized {
    let x = 0;
    #[coroutine]
    static || {
        yield;
        x
    }
}
```

We currently suggest prefixing `move` before `static`, which is
syntactically incorrect:

```
error[E0373]: coroutine may outlive the current function, but it borrows
...
 --> src/main.rs:6:5
  |
6 |     static || {
  |     ^^^^^^^^^ may outlive borrowed value `x`
7 |         yield;
8 |         x
  |         - `x` is borrowed here
  |
note: coroutine is returned here
 --> src/main.rs:6:5
  |
6 | /     static || {
7 | |         yield;
8 | |         x
9 | |     }
  | |_____^
help: to force the coroutine to take ownership of `x` (and any other
referenced variables), use the `move` keyword
  |     // this is syntactically incorrect, it should be `static move ||`
6 |     move static || {
  |     ++++

```

This PR suggests adding `move` after `static` for these coroutines.

I also added a UI test for this case.
2024-05-20 08:31:42 +02:00
Matthias Krüger 88552615e8
Rollup merge of #125282 - WaffleLapkin:never-type-unsafe-improvements, r=compiler-errors
Never type unsafe lint improvements

- Move linting code to a separate method
- Remove mentions of `core::convert::absurd` (#124311 was rejected)
- Make the lint into FCW

The last thing is a bit weird though. On one hand it should be `EditionSemanticsChange(2024)`, but on the other hand it shouldn't, because we also plan to break it on all editions some time later. _Also_, it's weird that we don't have `FutureReleaseSemanticsChangeReportInDeps`, IMO "this might cause UB in a future release" is important enough to be reported in deps...

IMO we ought to have three enums instead of [`FutureIncompatibilityReason`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_lint_defs/enum.FutureIncompatibilityReason.html#):

```rust
enum IncompatibilityWhen {
     FutureRelease,
     Edition(Edition),
}

enum IncompatibilyWhat {
    Error,
    SemanticChange,
}

enum IncompatibilityReportInDeps {
    No,
    Yes,
}
```

Tracking:
- https://github.com/rust-lang/rust/issues/123748
2024-05-20 08:31:41 +02:00
Caleb Zulawski 86158f581d Make repr(packed) vectors work with SIMD intrinsics 2024-05-20 01:09:29 -04:00
Michael Goulet 6b3058204a Force the inner coroutine of an async closure to move if the outer closure is move and FnOnce 2024-05-19 23:46:52 -04:00
Jubilee Young b6d0d6da55 note value of RUST_MIN_STACK and explain unsetting 2024-05-19 20:09:03 -07:00
Jubilee Young 9985821b2f defrost RUST_MIN_STACK=ice rustc hello.rs
An earlier commit included the change for a suggestion here.
Unfortunately, it also used unwrap instead of dying properly.
Roll out the ~~rice paper~~ EarlyDiagCtxt before we do anything that
might leave a mess.
2024-05-19 18:28:14 -07:00
Jubilee Young def6b99b4a move rustc-rust-log test into ui/rustc-env 2024-05-19 18:27:53 -07:00
Joshua Wong 371de042d9 add ui tests for E0373 suggestion 2024-05-19 19:23:38 -05:00
Matthias Krüger d5bef41ee5
Rollup merge of #124948 - blyxyas:remove-repeated-words, r=compiler-errors
chore: Remove repeated words (extension of #124924)

When I saw #124924 I thought "Hey, I'm sure that there are far more than just two typos of this nature in the codebase". So here's some more typo-fixing.

Some found with regex, some found with a spellchecker. Every single one manually reviewed by me (along with hundreds of false negatives by the tools)
2024-05-19 22:50:55 +02:00
Urgau 3b47f4c60c Refer to the Cargo specific doc in the check-cfg diagnostics 2024-05-19 20:12:41 +02:00
Urgau 7cb84fbf14 Prefer suggesting string-literal for Cargo check-cfg lint config 2024-05-19 20:04:32 +02:00
Waffle Lapkin 434221ba45 bless tests 2024-05-19 19:10:04 +02:00
Georg Semmler 9b45cfdbdd
Actually use the #[do_not_recommend] attribute if present
This change tweaks the error message generation to actually use the
`#[do_not_recommend]` attribute if present by just skipping the marked
trait impl in favour of the parent impl. It also adds a compile test for
this behaviour. Without this change the test would output the following
error:

```
error[E0277]: the trait bound `&str: Expression` is not satisfied
  --> /home/weiznich/Documents/rust/rust/tests/ui/diagnostic_namespace/do_not_recommend.rs:53:15
   |
LL |     SelectInt.check("bar");
   |               ^^^^^ the trait `Expression` is not implemented for `&str`, which is required by `&str: AsExpression<Integer>`
   |
   = help: the following other types implement trait `Expression`:
             Bound<T>
             SelectInt
note: required for `&str` to implement `AsExpression<Integer>`
  --> /home/weiznich/Documents/rust/rust/tests/ui/diagnostic_namespace/do_not_recommend.rs:26:13
   |
LL | impl<T, ST> AsExpression<ST> for T
   |             ^^^^^^^^^^^^^^^^     ^
LL | where
LL |     T: Expression<SqlType = ST>,
   |        ------------------------ unsatisfied trait bound introduced here
```

Note how that mentions `&str: Expression` before and now mentions `&str:
AsExpression<Integer>` instead which is much more helpful for users.

Open points for further changes before stabilization:

* We likely want to move the attribute to the `#[diagnostic]` namespace
to relax the guarantees given?
* How does it interact with the new trait solver?
2024-05-19 08:29:27 +02:00
Jubilee Young 1914c722b5 compiler: add simd_ctpop intrinsic 2024-05-18 18:11:20 -07:00
bors b1ec1bd65f Auto merge of #125257 - jieyouxu:rollup-11evnm9, r=jieyouxu
Rollup of 3 pull requests

Successful merges:

 - #125214 (Only make GAT ambiguous in `match_projection_projections` considering shallow resolvability)
 - #125236 (Add tests for `-Zunpretty=expanded` ported from stringify's tests)
 - #125251 (Clarify how String::leak and into_boxed_str differ )

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-18 21:45:06 +00:00
许杰友 Jieyou Xu (Joe) ffc04dfcc6
Rollup merge of #125236 - dtolnay:expandtest, r=nnethercote
Add tests for `-Zunpretty=expanded` ported from stringify's tests

This PR adds a new set of tests for the AST pretty-printer.

Previously, pretty-printer edge cases were tested by way of `stringify!` in [tests/ui/macros/stringify.rs](https://github.com/rust-lang/rust/blob/1.78.0/tests/ui/macros/stringify.rs), such as the tests added by 419b26931b and 527e2eac17.

Those tests will no longer provide effective coverage of the AST pretty-printer after #124141. `Nonterminal` and `TokenKind::Interpolated` are being removed, and a consequence is that `stringify!` will perform token stream pretty printing, instead of AST pretty printing, in all of the `stringify!` cases including $:expr and all other interpolations.

This PR adds 2 new ui tests with `compile-flags: -Zunpretty=expanded`:

- **tests/ui/unpretty/expanded-exhaustive.rs** &mdash; this test aims for exhaustive coverage of all the variants of `ExprKind`, `ItemKind`, `PatKind`, `StmtKind`, `TyKind`, and `VisibilityKind`. Some parts could use being fleshed out further, but the current state is roughly on par with what exists in the old stringify-based tests.

- **tests/ui/unpretty/expanded-interpolation.rs** &mdash; this test covers tricky macro metavariable edge cases that require the AST pretty printer to synthesize parentheses in order for the printed code to be valid Rust syntax.

r? `@nnethercote`
2024-05-18 20:38:05 +01:00
许杰友 Jieyou Xu (Joe) f08746a95d
Rollup merge of #125214 - compiler-errors:gat-guide, r=lcnr
Only make GAT ambiguous in `match_projection_projections` considering shallow resolvability

In #123537, I tweaked the hack from #93892 to use `resolve_vars_if_possible` instead of `shallow_resolve`. This considers more inference guidance ambiguous. This resulted in crater regressions in #125196.

I've effectively reverted the change to the old behavior. That being said, I don't *like* this behavior, but I'd rather keep it for now since #123537 was not meant to make any behavioral changes. See the attached example.

This also affects the new solver, for the record, which doesn't have any rules about not guiding inference from param-env candidates which may constrain GAT args as a side-effect.

r? `@lcnr` or `@jackh726`
2024-05-18 20:38:04 +01:00
bors eb1a5c9bb3 Auto merge of #125077 - spastorino:add-new-fnsafety-enum2, r=jackh726
Rename Unsafe to Safety

Alternative to #124455, which is to just have one Safety enum to use everywhere, this opens the posibility of adding `ast::Safety::Safe` that's useful for unsafe extern blocks.

This leaves us today with:

```rust
enum ast::Safety {
    Unsafe(Span),
    Default,
    // Safe (going to be added for unsafe extern blocks)
}

enum hir::Safety {
    Unsafe,
    Safe,
}
```

We would convert from `ast::Safety::Default` into the right Safety level according the context.
2024-05-18 19:35:24 +00:00
David Tolnay 3e05be5466
Add tests for -Zunpretty=expanded ported from stringify's tests 2024-05-18 10:36:02 -07:00
Michael Goulet 5ee4db4e05 Warn/error on self ctor from outer item in inner item 2024-05-18 13:08:34 -04:00
Michael Goulet 2e97dae8d4 An async closure may implement FnMut/Fn if it has no self-borrows 2024-05-18 12:47:59 -04:00
Matthias Krüger f9bf759e83
Rollup merge of #125117 - dev-ardi:improve-parser, r=wesleywiser,fmease
Improve parser

Fixes #124935.

- Add a few more help diagnostics to incorrect semicolons
- Overall improved that function
- Addded a few comments
- Renamed diff_marker fns to git_diff_marker
2024-05-18 18:44:14 +02:00
blyxyas c5c820e7fb Fix typos (taking into account review comments) 2024-05-18 18:12:18 +02:00
bors 685a80f7a0 Auto merge of #125180 - mu001999-contrib:improve/macro-diag, r=fee1-dead
Improve error message: missing `;` in macro_rules

Fixes #124968
2024-05-18 13:02:48 +00:00
r0cky c2be1342b7 Improve error message: missing ; in macro_rules 2024-05-18 18:56:12 +08:00
bors 1c90b9fe6e Auto merge of #125004 - pymongo:issue-125002, r=estebank
Fix println! ICE when parsing percent prefix number

This PR fixes #125002 ICE occurring, for example, with `println!("%100000", 1)` or `println!("%    100000", 1)`.

## Test Case/Change Explanation

The return type of `Num::from_str` has been changed to `Option<Self>` to handle errors when parsing large integers fails.

1. The first `println!` in the test case covers the change of the first `Num::from_str` usage in `format_foreign.rs:426`.
2. The second `println!` in the test case covers the change of the second `Num::from_str` usage in line 460.
3. The 3rd to 5th `Num::from_str` usages behave the same as before.

The 3rd usage would cause an ICE when `num > u16::MAX` in the previous version, but this commit does not include a fix for the ICE in `println!("{:100000$}")`. I think we need to emit an error in the compiler and have more discussion in another issue/PR.
2024-05-18 08:44:01 +00:00
bors 36c0a6d40f Auto merge of #125105 - nnethercote:rustc_resolve-cleanups, r=estebank
`rustc_resolve` cleanups

Some improvements I found while looking through this code.

r? `@estebank`
2024-05-18 06:36:44 +00:00
wuaoxiang 582fd1fb53 Fix println! ICE when parsing percent prefix number 2024-05-18 01:05:56 +00:00
bors 9b75a43881 Auto merge of #123865 - eholk:expr_2021, r=fmease
Update `expr` matcher for Edition 2024 and add `expr_2021` nonterminal

This commit adds a new nonterminal `expr_2021` in macro patterns, and `expr_fragment_specifier_2024` feature flag.

This change also updates `expr` so that on Edition 2024 it will also match `const { ... }` blocks, while `expr_2021` preserves the current behavior of `expr`, matching expressions without `const` blocks.

Joint work with `@vincenzopalazzo.`

Issue #123742
2024-05-17 21:54:14 +00:00
Santiago Pastorino 6b46a919e1
Rename Unsafe to Safety 2024-05-17 18:33:37 -03:00
Esteban Küber cf5702ee91 Detect when a lifetime is being reused in suggestion 2024-05-17 21:23:47 +00:00
Esteban Küber 1775e7b93d Tweak suggested lifetimes to modify return type instead of &self receiver
Do not suggest constraining the `&self` param, but rather the return type.
If that is wrong (because it is not sufficient), a follow up error will tell the
user to fix it. This way we lower the chances of *over* constraining, but still
get the cake of "correctly" contrained in two steps.

This is a correct suggestion:

```
error: lifetime may not live long enough
  --> $DIR/ex3-both-anon-regions-return-type-is-anon.rs:9:9
   |
LL |     fn foo<'a>(&self, x: &i32) -> &i32 {
   |                -         - let's call the lifetime of this reference `'1`
   |                |
   |                let's call the lifetime of this reference `'2`
LL |         x
   |         ^ method was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
   |
help: consider introducing a named lifetime parameter and update trait if needed
   |
LL |     fn foo<'a>(&self, x: &'a i32) -> &'a i32 {
   |                           ++          ++
```

While this is incomplete because it should suggestino `&'a self`

```
error: lifetime may not live long enough
  --> $DIR/ex3-both-anon-regions-self-is-anon.rs:7:19
   |
LL |     fn foo<'a>(&self, x: &Foo) -> &Foo {
   |                -         - let's call the lifetime of this reference `'1`
   |                |
   |                let's call the lifetime of this reference `'2`
LL |         if true { x } else { self }
   |                   ^ method was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
   |
help: consider introducing a named lifetime parameter and update trait if needed
   |
LL |     fn foo<'a>(&self, x: &'a Foo) -> &'a Foo {
   |                           ++          ++
```

but the follow up error is

```
error: lifetime may not live long enough
 --> tests/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-self-is-anon.rs:7:30
  |
6 |     fn foo<'a>(&self, x: &'a Foo) -> &'a Foo {
  |            --  - let's call the lifetime of this reference `'1`
  |            |
  |            lifetime `'a` defined here
7 |         if true { x } else { self }
  |                              ^^^^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
  |
help: consider introducing a named lifetime parameter and update trait if needed
  |
6 |     fn foo<'a>(&'a self, x: &'a Foo) -> &'a Foo {
  |                 ++
```
2024-05-17 20:31:13 +00:00
Esteban Küber ee5a157b4a Run rustfmt on modified tests 2024-05-17 20:31:13 +00:00
Esteban Küber d1d585d039 Account for owning item lifetimes in suggestion and annotate tests as run-rustfix
```
error: lifetime may not live long enough
  --> $DIR/lt-ref-self.rs:12:9
   |
LL |     fn ref_self(&self, f: &u32) -> &u32 {
   |                 -         - let's call the lifetime of this reference `'1`
   |                 |
   |                 let's call the lifetime of this reference `'2`
LL |         f
   |         ^ method was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
   |
help: consider introducing a named lifetime parameter and update trait if needed
   |
LL |     fn ref_self<'b>(&'b self, f: &'b u32) -> &'b u32 {
   |                ++++  ++           ++          ++
```
2024-05-17 20:31:13 +00:00
Esteban Küber 120049fab4 Always constrain the return type in lifetime suggestion
```
error: lifetime may not live long enough
 --> f205.rs:8:16
  |
7 |     fn resolve_symbolic_reference(&self, reference: Option<Reference>) -> Option<Reference> {
  |                                   -      --------- has type `Option<Reference<'1>>`
  |                                   |
  |                                   let's call the lifetime of this reference `'2`
8 |         return reference;
  |                ^^^^^^^^^ method was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
  |
help: consider introducing a named lifetime parameter
  |
7 |     fn resolve_symbolic_reference<'a>(&'a self, reference: Option<Reference<'a>>) -> Option<Reference<'a>> {
  |                                  ++++  ++                                  ++++                      ++++
```

The correct suggestion would be

```
help: consider introducing a named lifetime parameter
  |
7 |     fn resolve_symbolic_reference<'a>(&self, reference: Option<Reference<'a>>) -> Option<Reference<'a>> {
  |                                  ++++                                   ++++                      ++++
```

but we are not doing the analysis to detect that yet. If we constrain `&'a self`, then the return type with a borrow will implicitly take its lifetime from `'a`, it is better to make it explicit in the suggestion, in case that `&self` *doesn't* need to be `'a`, but the return does.
2024-05-17 20:31:13 +00:00
Esteban Küber 9f730e92f2 Suggest setting lifetime in borrowck error involving types with elided lifetimes
```
error: lifetime may not live long enough
  --> $DIR/ex3-both-anon-regions-both-are-structs-2.rs:7:5
   |
LL | fn foo(mut x: Ref, y: Ref) {
   |        -----       - has type `Ref<'_, '1>`
   |        |
   |        has type `Ref<'_, '2>`
LL |     x.b = y.b;
   |     ^^^^^^^^^ assignment requires that `'1` must outlive `'2`
   |
help: consider introducing a named lifetime parameter
   |
LL | fn foo<'a>(mut x: Ref<'a, 'a>, y: Ref<'a, 'a>) {
   |       ++++           ++++++++        ++++++++
```

As can be seen above, it currently doesn't try to compare the `ty::Ty` lifetimes that diverged vs the `hir::Ty` to correctly suggest the following

```
help: consider introducing a named lifetime parameter
   |
LL | fn foo<'a>(mut x: Ref<'_, 'a>, y: Ref<'_, 'a>) {
   |       ++++           ++++++++        ++++++++
```

but I believe this to still be an improvement over the status quo.

CC #40990.
2024-05-17 20:31:13 +00:00
Michael Goulet fa829feb2f Only make GAT ambiguous in match_projection_projections considering shallow resolvability 2024-05-17 12:51:21 -04:00
Matthias Krüger 3695449a89
Rollup merge of #125191 - compiler-errors:wf, r=lcnr
Report better WF obligation leaf obligations in new solver

r? lcnr
2024-05-17 07:20:59 +02:00
Matthias Krüger e62688eb96
Rollup merge of #123694 - Xiretza:expand-diagnostics, r=compiler-errors
expand: fix minor diagnostics bug

The error mentions `///`, when it's actually `//!`:

```
error[E0658]: attributes on expressions are experimental
 --> test.rs:4:9
  |
4 |         //! wah
  |         ^^^^^^^
  |
  = note: see issue https://github.com/rust-lang/rust/issues/15701 <https://github.com/rust-lang/rust/issues/15701> for more information
  = help: add `#![feature(stmt_expr_attributes)]` to the crate attributes to enable
  = help: `///` is for documentation comments. For a plain comment, use `//`.
```
2024-05-17 07:20:56 +02:00
Michael Goulet 119c7bbef7 Report better WF obligation leaf obligations in new solver 2024-05-16 21:08:42 -04:00
Urgau 05f77d1b79 Update unexpected_cfgs lint for Cargo new check-cfg config 2024-05-16 20:58:22 +02:00