Commit Graph

32931 Commits

Author SHA1 Message Date
Nicholas Nethercote c1ffb0b675 Remove `force_print_diagnostic`.
There are a couple of places where we call
`inner.emitter.emit_diagnostic` directly rather than going through
`inner.emit_diagnostic`, to guarantee the diagnostic is printed. This
feels dubious to me, particularly the bypassing of `TRACK_DIAGNOSTIC`.

This commit removes those.
- In `print_error_count`, it uses `ForceWarning` instead of `Warning`.
- It removes `DiagCtxtInner::failure_note`, because it only has three
  uses and direct use of `emit_diagnostic` is consistent with other
  similar locations.
- It removes `force_print_diagnostic`, and adds `struct_failure_note`,
  and updates `print_query_stack` accordingly, which makes it more
  normal. That location doesn't seem to need forced printing anyway.
2024-02-14 07:51:53 +11:00
Nicholas Nethercote bdc6d82f9a Make `struct_span_note` call `struct_note`.
So it follows the same pattern as all the other `struct_span_*` methods.
2024-02-14 07:50:54 +11:00
Esteban Küber 24b52fd9df Do not point at `#[allow(_)]` as the reason for compat lint triggering
Fix #121009.
2024-02-13 20:27:43 +00:00
Michael Goulet b4eee2e8b3 Do not assemble candidates for default impls 2024-02-13 19:20:13 +00:00
bors a84bb95a1f Auto merge of #121036 - matthiaskrgr:rollup-ul05q8e, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #114877 (unstable-book: add quick-edit link)
 - #120548 (rustdoc: Fix handling of doc_auto_cfg feature for cfg attributes on glob reexport)
 - #120549 (modify alias-relate to also normalize ambiguous opaques)
 - #120959 (Remove good path delayed bugs)
 - #120978 (match lowering: simplify block creation)
 - #121019 (coverage: Simplify some parts of the coverage span refiner)
 - #121021 (Extend intra-doc link chapter in the rustdoc book)
 - #121031 (RustWrapper: adapt for coverage mapping API changes)

Failed merges:

 - #121014 (Remove `force_print_diagnostic`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-13 17:27:25 +00:00
Camille GILLOT a97e4afb67 Fix handling of adjustment casts. 2024-02-13 17:22:56 +00:00
Matthias Krüger 8dffa39367
Rollup merge of #121031 - TimNN:lh-fix-20240213, r=durin42
RustWrapper: adapt for coverage mapping API changes

There've been a number of changes to the coverage mapping API today, but the end result is that specifying the MCDC parameters is now optional (they've been moved to the end of the argument list and now default to `std::monostate`).

`@rustbot` label: +llvm-main

r? `@durin42`
2024-02-13 17:38:12 +01:00
Matthias Krüger e36a7f4c65
Rollup merge of #121019 - Zalathar:covspans, r=oli-obk
coverage: Simplify some parts of the coverage span refiner

This is another incremental step on my quest to dismantle the coverage span refiner into something more understandable and maintainable.

The biggest change here is splitting up `CoverageSpan` into several more specific structs. Doing so reveals that most of the places that were using that struct only need a subset of its fields and methods.

We can also get rid of separate tracking of `curr_original_span` and `prev_original_span`, by observing that `curr.span` never actually needs to be mutated, and that we can store `prev_original_span` directly in the dedicated struct for `prev`.

`@rustbot` label +A-code-coverage
2024-02-13 17:38:11 +01:00
Matthias Krüger b785fdb80b
Rollup merge of #120978 - Nadrieril:sane-blocks, r=matthewjasper
match lowering: simplify block creation

Match lowering was doing complicated things with block creation. As far as I can tell it was trying to avoid creating unneeded blocks, but of the three places that start out with `otherwise = &mut None`, two of them called `otherwise.unwrap_or_else(|| self.cfg.start_new_block())` anyway. As far as I can tell the only place where this PR makes a difference is in `lower_match_tree`, which did indeed sometimes avoid creating the unreachable final block + FakeRead. Unless this is important I propose we do the naive thing instead.

I have not checked all the graph isomorphisms by hand, but at a glance the test diff looks sensible.

r? `@matthewjasper`
2024-02-13 17:38:11 +01:00
Matthias Krüger 93e9579b5d
Rollup merge of #120959 - nnethercote:rm-good_path, r=oli-obk
Remove good path delayed bugs

Because they're not that useful, and kind of annoying. Details in the individual commits.

r? ```@compiler-errors```
2024-02-13 17:38:10 +01:00
Matthias Krüger 65ab663266
Rollup merge of #120549 - lcnr:errs-showcase, r=compiler-errors
modify alias-relate to also normalize ambiguous opaques

allows a bunch of further cleanups and generally simplifies the type system. To handle https://github.com/rust-lang/trait-system-refactor-initiative/issues/8 we'll have to add a some additional complexity to the `(Alias, Infer)` branches in alias-relate, so removing the opaque type special case here is really valuable.

It does worsen `deduce_closure_signature` and friends even more as they now receive an inference variable which is only constrained via an `AliasRelate` goal. These probably have to look into alias relate goals somehow. Leaving that for a future PR as this is something we'll have to tackle regardless.

r? `@compiler-errors`
2024-02-13 17:38:10 +01:00
Michael Goulet 2b4a2b95dd Check normalized call signature for WF in mir typeck 2024-02-13 16:00:01 +00:00
Michael Goulet 7e80867f3c Move visitable bounds up into interner 2024-02-13 15:53:15 +00:00
Michael Goulet edc5053352 Add assertions back to canonicalizer 2024-02-13 15:40:59 +00:00
Michael Goulet f4e886323c Uplift TypeVisitableExt into rustc_type_ir 2024-02-13 15:40:55 +00:00
bors eaff1af8fd Auto merge of #120055 - nikic:llvm-18, r=cuviper
Update to LLVM 18

LLVM 18 final is planned to be released on Mar 5th. Rust 1.78 is planned to be released on May 2nd.

Tested images: dist-x86_64-linux, dist-s390x-linux, dist-aarch64-linux, dist-riscv64-linux, dist-loongarch64-linux, dist-x86_64-freebsd, dist-x86_64-illumos, dist-x86_64-musl, x86_64-linux-integration, test-various, armhf-gnu, i686-msvc, x86_64-msvc, i686-mingw, x86_64-mingw, x86_64-apple-1, x86_64-apple-2, dist-aarch64-apple

r? `@ghost`
2024-02-13 15:07:28 +00:00
Tim Neumann 14ec3b6c91 RustWrapper: adapt for coverage mapping API changes 2024-02-13 15:15:14 +01:00
Zalathar e67db4c3b8 coverage: Simplify code for adding `prev` to pending dups
If we only check for duplicate spans when `prev` is unmodified, we reduce the
number of situations that `update_pending_dups` needs to handle.

This could potentially change the coverage spans we produce in some unknown
corner cases, but none of our current coverage tests indicate any change.
2024-02-13 21:48:03 +11:00
Zalathar 499609d8a4 coverage: Move `prev_original_span` into `PrevCovspan`
Now that `prev` has its own dedicated struct, we can store the original span in
that struct, instead of in a separate field in the refiner.
2024-02-13 21:48:03 +11:00
Zalathar a6183216d8 coverage: Split `CoverageSpan` into several distinct structs
This requires some extra boilerplate, but in exchange it becomes much easier to
see how each field and method is actually used.
2024-02-13 21:48:03 +11:00
Oli Scherer d3a89cd214 Avoid an ICE in diagnostics 2024-02-13 10:44:54 +00:00
Oli Scherer 7320623f3a Just pass the checker instead of individual fields 2024-02-13 10:23:06 +00:00
Oli Scherer 251c33ce2a Remove an `impl_polarity` call where the information is already available in the header 2024-02-13 10:18:05 +00:00
Zalathar 5a569b1b80 coverage: Don't track `curr_original_span` explicitly
Now that we never mutate `curr.span`, we don't need to store its original span
separately.
2024-02-13 21:01:17 +11:00
Zalathar 412c86cf03 coverage: When merging spans, keep `prev` and merge `curr` into it
Swapping the direction of this merge produces the same results, but means that
we never need to mutate `curr`.
2024-02-13 21:01:17 +11:00
Oli Scherer 75de6cf9a3 Avoid using the HIR span in the happy path 2024-02-13 09:49:08 +00:00
Oli Scherer 40b3cb0eb1 Don't reinvoke `trait_header` query twice 2024-02-13 09:38:13 +00:00
Nikita Popov a911c8ce23 Use MCSubtargetInfo::getAllProcessorFeatures()
This method is now available in upstream LLVM \o/
2024-02-13 10:33:40 +01:00
Oli Scherer 55bbb054c9 Invoke `trait_def` query only once
This may be a small performance boost as we have to hash less to lookup the value
2024-02-13 09:29:31 +00:00
Oli Scherer 11a73f6d4d Store impl unsafety in impl trait header 2024-02-13 09:21:34 +00:00
Matthias Krüger 70ea26d349
Rollup merge of #120995 - durin42:llvm-19-pgo-coldfuncopt, r=cuviper
PassWrapper: adapt for llvm/llvm-project@93cdd1b5cf

Should be no functional change.

`@rustbot` label: +llvm-main
2024-02-13 06:27:41 +01:00
Matthias Krüger 21d8fb272b
Rollup merge of #120988 - tshepang:fix-comment, r=cjgillot
fix comment
2024-02-13 06:27:41 +01:00
Matthias Krüger 7427460ea9
Rollup merge of #120987 - tshepang:redundant, r=compiler-errors
remove redundant logic

Made redundant in 3f697b85f2
2024-02-13 06:27:40 +01:00
Matthias Krüger fa3ec02057
Rollup merge of #120974 - zmodem:exportas, r=durin42
llvm-wrapper: adapt for LLVM API change: Add support for EXPORTAS name types

Adapt for llvm/llvm-project@8f23464.
2024-02-13 06:27:39 +01:00
Matthias Krüger 30057f0266
Rollup merge of #120802 - oli-obk:drop_elab_ice, r=compiler-errors
Bail out of drop elaboration when encountering error types

fixes  #120788
2024-02-13 06:27:38 +01:00
Matthias Krüger 1b396913a9
Rollup merge of #120751 - estebank:issue-68982, r=nnethercote
Provide more suggestions on invalid equality where bounds

```
error: equality constraints are not yet supported in `where` clauses
  --> $DIR/equality-bound.rs:50:9
   |
LL |         IntoIterator::Item = A
   |         ^^^^^^^^^^^^^^^^^^^^^^ not supported
   |
   = note: see issue #20041 <https://github.com/rust-lang/rust/issues/20041> for more information
help: if `IntoIterator::Item` is an associated type you're trying to set, use the associated type binding syntax
   |
LL ~     fn from_iter<T: IntoIterator<Item = A>>(_: T) -> Self
LL ~
   |

error: equality constraints are not yet supported in `where` clauses
  --> $DIR/equality-bound.rs:63:9
   |
LL |         T::Item = A
   |         ^^^^^^^^^^^ not supported
   |
   = note: see issue #20041 <https://github.com/rust-lang/rust/issues/20041> for more information
help: if `IntoIterator::Item` is an associated type you're trying to set, use the associated type binding syntax
   |
LL ~     fn from_iter<T: IntoIterator<Item = A>>(_: T) -> Self
LL ~
   |
```

Fix #68982.
2024-02-13 06:27:37 +01:00
Matthias Krüger 020e84652d
Rollup merge of #120696 - estebank:issue-115405, r=oli-obk
Properly handle `async` block and `async fn` in `if` exprs without `else`

When encountering a tail expression in the then arm of an `if` expression without an `else` arm, account for `async fn` and `async` blocks to suggest `return`ing the value and pointing at the return type of the `async fn`.

We now also account for AFIT when looking for the return type to point at.

Fix #115405.
2024-02-13 06:27:37 +01:00
lcnr ae92334c0f remove questionable calls to `commit_if_ok` 2024-02-13 05:44:46 +01:00
lcnr 3e3e207ad7 use alias-relate to structurally normalize in the solver 2024-02-13 05:08:51 +01:00
lcnr bbe2f6c0b2 also try to normalize opaque types in alias-relate
with this, alias-relate treats all aliases the same way
and it can be used for structural normalization.
2024-02-13 04:47:32 +01:00
bors d26b417112 Auto merge of #120919 - oli-obk:impl_polarity, r=compiler-errors
Merge `impl_polarity` and `impl_trait_ref` queries

Hopefully this is perf neutral. I want to finish https://github.com/rust-lang/rust/pull/120835 and stop using the HIR in `coherent_trait`, which should then give us a perf improvement.
2024-02-13 02:48:49 +00:00
bors 0a5b998c57 Auto merge of #120991 - matthiaskrgr:rollup-f8kw2st, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #118983 (Warn on references casting to bigger memory layout)
 - #119451 (Gate PR CI on clippy correctness lints)
 - #120273 (compiletest: few naive improvements)
 - #120950 (Fix async closures in CTFE)
 - #120958 (Dejargonize `subst`)
 - #120965 (Add lahfsahf and prfchw target feature)
 - #120970 (add another test for promoteds-in-static)
 - #120979 (Update books)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-13 00:31:53 +00:00
Augie Fackler 9d1bd2e067 PassWrapper: adapt for llvm/llvm-project@93cdd1b5cf
Should be no functional change.

@rustbot label: +llvm-main
2024-02-12 19:13:09 -05:00
Nicholas Nethercote 9f2aa09765 Remove `good_path_delayed_bug`.
It's only has a single remaining purpose: to ensure that a diagnostic is
printed when `trimmed_def_paths` is used. It's an annoying mechanism:
weak, with odd semantics, badly named, and gets in the way of other
changes.

This commit replaces it with a simpler `must_produce_diag` mechanism,
getting rid of a diagnostic `Level` along the way.
2024-02-13 09:33:35 +11:00
Matthias Krüger 7075502b15
Rollup merge of #120965 - ChrisDenton:sahf, r=michaelwoerister
Add lahfsahf and prfchw target feature

This adds target features for LAHF/SAHF and PrefetchW. These came up. along with the existing CMPXCHG16b. as [baseline features](https://download.microsoft.com/download/c/1/5/c150e1ca-4a55-4a7e-94c5-bfc8c2e785c5/Windows%2010%20Minimum%20Hardware%20Requirements.pdf) required for x86_64 Windows 10+.
2024-02-12 23:18:54 +01:00
Matthias Krüger cb0d74be28
Rollup merge of #120958 - ShoyuVanilla:remove-subst, r=oli-obk
Dejargonize `subst`

In favor of #110793, replace almost every occurence of `subst` and `substitution` from rustc codes, but they still remains in subtrees under `src/tools/` like clippy and test codes (I'd like to replace them after this)
2024-02-12 23:18:54 +01:00
Matthias Krüger 15896bdd18
Rollup merge of #120950 - compiler-errors:miri-async-closurs, r=RalfJung,oli-obk
Fix async closures in CTFE

First commit renames `is_coroutine_or_closure` into `is_closure_like`, because `is_coroutine_or_closure_or_coroutine_closure` seems confusing and long.

Second commit fixes some forgotten cases where we want to handle `TyKind::CoroutineClosure` the same as closures and coroutines.

The test exercises the change to `ValidityVisitor::aggregate_field_path_elem` which is the source of #120946, but not the change to `UsedParamsNeedSubstVisitor`, though I feel like it's not that big of a deal. Let me know if you'd like for me to look into constructing a test for the latter, though I have no idea what it'd look like (we can't assert against `TooGeneric` anywhere?).

Fixes #120946

r? oli-obk cc ``@RalfJung``
2024-02-12 23:18:53 +01:00
Matthias Krüger 74f5e1f140
Rollup merge of #118983 - Urgau:invalid_ref_casting-bigger-layout, r=oli-obk
Warn on references casting to bigger memory layout

This PR extends the [`invalid_reference_casting`](https://doc.rust-lang.org/rustc/lints/listing/deny-by-default.html#invalid-reference-casting) lint (*deny-by-default*) which currently lint on `&T -> &mut T` casting to also lint on `&(mut) A -> &(mut) B` where `size_of::<B>() > size_of::<A>()` (bigger memory layout requirement).

The goal is to detect such cases:

```rust
let u8_ref: &u8 = &0u8;
let u64_ref: &u64 = unsafe { &*(u8_ref as *const u8 as *const u64) };
//~^ ERROR casting references to a bigger memory layout is undefined behavior

let mat3 = Mat3 { a: Vec3(0i32, 0, 0), b: Vec3(0, 0, 0), c: Vec3(0, 0, 0) };
let mat3 = unsafe { &*(&mat3 as *const _ as *const [[i64; 3]; 3]) };
//~^ ERROR casting references to a bigger memory layout is undefined behavior
```

This is added to help people who write unsafe code, especially when people have matrix struct that they cast to simple array of arrays.

EDIT: One caveat, due to the [`&Header`](https://github.com/rust-lang/unsafe-code-guidelines/issues/256) uncertainty the lint only fires when it can find the underline allocation.

~~I have manually tested all the new expressions that warn against Miri, and they all report immediate UB.~~

r? ``@est31``
2024-02-12 23:18:52 +01:00
bors 74c3f5a146 Auto merge of #120324 - Nadrieril:remove-interior-mutability, r=compiler-errors
pattern_analysis: track usefulness without interior mutability

Because of or-patterns, exhaustiveness needs to be able to lint if a sub-pattern is redundant, e.g. in `Some(_) | Some(true)`. So far the only sane solution I had found was interior mutability. This is a bit of an abstraction leak, and would become a footgun if we ever reused the same `DeconstructedPat`. This PR replaces interior mutability with an address-indexed hashmap, which is logically equivalent.
2024-02-12 22:16:58 +00:00
Nicholas Nethercote 173dbc9e13 Remove `TypeErrCtxt::drop`.
The check within changed from `delay_span_bug` to `delay_good_path_bug`
in #110476, and removing the check altogether was considered. It's a
very weak sanity check and gets in the way of removing good path delayed
bugs altogether, so this PR just removes it.
2024-02-13 08:34:42 +11:00
Tshepang Mbambo 882396cbd0 fix comment 2024-02-12 23:22:49 +02:00
demilade e99766d885 suggest `into_iter()` when `Iterator` method called on `impl IntoIterator` 2024-02-12 22:11:48 +01:00
Tshepang Mbambo c51b9ff8ba remove redundant logic
Made redundant in 3f697b85f2
2024-02-12 23:08:00 +02:00
Esteban Küber d07195fe6b Remove visitor use 2024-02-12 20:26:40 +00:00
Esteban Küber 37d2ea2fa0 Properly handle `async` blocks and `fn`s in `if` exprs without `else`
When encountering a tail expression in the then arm of an `if` expression
without an `else` arm, account for `async fn` and `async` blocks to
suggest `return`ing the value and pointing at the return type of the
`async fn`.

We now also account for AFIT when looking for the return type to point at.

Fix #115405.
2024-02-12 20:26:34 +00:00
Mohammad Omidvar 213748749e Add APIs for fetching foreign items including foreign modules, their ABIs, and their items 2024-02-12 19:44:35 +00:00
Urgau 6a8f50e907 Introduce small cache to avoid recomputing the same value twice 2024-02-12 19:40:17 +01:00
Urgau 915200fbe0 Lint on reference casting to bigger underlying allocation 2024-02-12 19:40:17 +01:00
Oli Scherer f35a2bd401 Support safe intrinsics with fallback bodies
Turn `is_val_statically_known` into such an intrinsic to demonstrate. It is perfectly safe to call after all.
2024-02-12 17:55:36 +00:00
Oli Scherer 6b73fe2d09 Give const_deallocate a default body 2024-02-12 17:52:05 +00:00
Oli Scherer 9a0743747f Teach llvm backend how to fall back to default bodies 2024-02-12 17:50:39 +00:00
Oli Scherer 432635a9ea Create ret_dest as late as possible in all code paths 2024-02-12 17:48:20 +00:00
Oli Scherer 55200e75da Do the entire ReturnDest computation within make_return_dest 2024-02-12 17:48:04 +00:00
Oli Scherer 8549c0a3e6 Add intrinsic body fallback to cranelift and use it 2024-02-12 17:44:55 +00:00
Oli Scherer 531505f182 Check signature of intrinsics with fallback bodies 2024-02-12 17:44:53 +00:00
bors b381d3ab27 Auto merge of #120980 - matthiaskrgr:rollup-dsjsqql, r=matthiaskrgr
Rollup of 11 pull requests

Successful merges:

 - #120765 (Reorder diagnostics API)
 - #120833 (More internal emit diagnostics cleanups)
 - #120899 (Gracefully handle non-WF alias in `assemble_alias_bound_candidates_recur`)
 - #120917 (Remove a bunch of dead parameters in functions)
 - #120928 (Add test for recently fixed issue)
 - #120933 (check_consts: fix duplicate errors, make importance consistent)
 - #120936 (improve `btree_cursors` functions documentation)
 - #120944 (Check that the ABI of the instance we are inlining is correct)
 - #120956 (Clean inlined type alias with correct param-env)
 - #120962 (Add myself to library/std review)
 - #120972 (fix ICE for deref coercions with type errors)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-12 17:06:22 +00:00
Matthias Krüger 8e5f722ece
Rollup merge of #120972 - lukas-code:autoderef-type-error, r=compiler-errors
fix ICE for deref coercions with type errors

Follow-up to https://github.com/rust-lang/rust/pull/120895, where I made types with errors go through the full coercion code, which is necessary if we want to build MIR for bodies with errors (https://github.com/rust-lang/rust/pull/120550).

The code for coercing `&T` to `&U` currently assumes that autoderef for `&T` will succeed for at least two steps (`&T` and `T`):

b17491c8f6/compiler/rustc_hir_typeck/src/coercion.rs (L339-L464)

But for types with errors, we previously only returned the no-op autoderef step (`&{type error}` -> `&{type error}`) and then stopped early. This PR changes autoderef for types with errors to still go through the built-in derefs (e.g. `&&{type error}` -> `&{type error}` -> `{type error}`) and only stop early when it would have to go looking for `Deref` trait impls.

fixes https://github.com/rust-lang/rust/issues/120945

r? ``@compiler-errors`` or compiler
2024-02-12 18:04:11 +01:00
Matthias Krüger 8ec144d738
Rollup merge of #120944 - compiler-errors:inliner-abi, r=oli-obk
Check that the ABI of the instance we are inlining is correct

When computing the `CallSite` in the mir inliner, double check that the instance of the function that we are inlining is compatible with the signature from the trait definition that we acquire from the MIR.

Fixes #120940

r? ``@oli-obk`` or ``@cjgillot``
2024-02-12 18:04:10 +01:00
Matthias Krüger 3f67169a5f
Rollup merge of #120933 - RalfJung:const-check-misc, r=oli-obk
check_consts: fix duplicate errors, make importance consistent

This is stuff I noticed while working on https://github.com/rust-lang/rust/pull/120932, but it's orthogonal to that PR.

r? ``@oli-obk``
2024-02-12 18:04:09 +01:00
Matthias Krüger ebe36ac815
Rollup merge of #120917 - chenyukang:yukang-dead-parameters, r=compiler-errors
Remove a bunch of dead parameters in functions

Found this kind of issue when working on https://github.com/rust-lang/rust/pull/119650
I wrote a trivial toy lint and manual review to find these.
2024-02-12 18:04:08 +01:00
Matthias Krüger 733f93d60c
Rollup merge of #120899 - compiler-errors:non-wf-alias, r=lcnr
Gracefully handle non-WF alias in `assemble_alias_bound_candidates_recur`

See explanation in test. I think it's fine to delay a bug here -- I don't believe we ever construct a non-wf alias on the good path? If so, then we can just remove the delay.

Fixes #120891

r? lcnr
2024-02-12 18:04:08 +01:00
Matthias Krüger f08ece38a8
Rollup merge of #120833 - nnethercote:more-internal-emit_diagnostics-cleanups, r=oli-obk
More internal emit diagnostics cleanups

Miscellaneous improvements.

r? ``@oli-obk``
2024-02-12 18:04:07 +01:00
Matthias Krüger 57a2e91ae8
Rollup merge of #120765 - nnethercote:reorder-diag-API, r=compiler-errors
Reorder diagnostics API

The totally random ordering of diagnostic methods in `DiagCtxt` has been low-key driving me crazy for a while now.

r? ``@compiler-errors``
2024-02-12 18:04:07 +01:00
Nadrieril faaf81bbbc Start blocks eagerly 2024-02-12 17:37:05 +01:00
Oli Scherer 0dac617a75 support adding const generic params to intrinsics
but right now all of them have zero const generic params
2024-02-12 15:22:42 +00:00
Oli Scherer 09fd556962 Make check_intrinsic_type not require ForeignItems anymore 2024-02-12 15:22:36 +00:00
bors bdc15928c8 Auto merge of #115367 - frank-king:feature/unnamed-fields-hir, r=davidtwco
Lowering unnamed fields and anonymous adt

This implements #49804.

Goals:
- [x] lowering anonymous ADTs from AST to HIR
- [x] generating definitions of anonymous ADTs
- [x] uniqueness check of the unnamed fields
- [x] field projection of anonymous ADTs
- [x] `#[repr(C)]` check of the anonymous ADTs

Non-Goals (will be in the next PRs)
- capturing generic params for the anonymous ADTs from the parent ADT
- pattern matching of anonymous ADTs
- structural expressions of anonymous ADTs
- rustdoc support of anonymous ADTs
2024-02-12 14:51:15 +00:00
Hans Wennborg 718b304d82 llvm-wrapper: adapt for LLVM API change: Add support for EXPORTAS name types
Adapt for llvm/llvm-project@8f23464.
2024-02-12 15:23:50 +01:00
Lukas Markeffsky 95c5b06000 fix ICE for deref coercions with type errors 2024-02-12 14:37:35 +01:00
Chris Denton 83a850f2a1
Add lahfsahf and prfchw target feature 2024-02-12 10:31:12 -03:00
bors ed19532868 Auto merge of #120960 - RalfJung:static-promoted-cycle, r=oli-obk
fix cycle error when a static and a promoted are mutually recursive

This also now allows promoteds everywhere to point to 'extern static', because why not? We still check that constants cannot transitively reach 'extern static' through references. (We allow it through raw pointers.)

r? `@oli-obk`
Fixes https://github.com/rust-lang/rust/issues/120949
2024-02-12 12:09:20 +00:00
Oli Scherer 79daf6107c Make the signature of equate_intrinsic_type support items other than `ForeignItem` 2024-02-12 09:52:12 +00:00
Oli Scherer 74c9dffac3 Remove impl_polarity query 2024-02-12 09:44:45 +00:00
Oli Scherer 92281c7e81 Implement intrinsics with fallback bodies 2024-02-12 09:44:22 +00:00
Oli Scherer b43fbe63e7 Stop calling `impl_polarity` when `impl_trait_ref` was also called 2024-02-12 09:44:09 +00:00
Oli Scherer ab0e8b3145 Eagerly dismiss binder 2024-02-12 09:43:54 +00:00
Oli Scherer a9e0e968be Unwrap an Option that can only be Some, as inherent impls can't overlap 2024-02-12 09:43:39 +00:00
Oli Scherer 90a43f1406 Use a struct instead of a tuple 2024-02-12 09:43:09 +00:00
Oli Scherer 916951efcc Make impl_trait_ref into a query also returning more information about the impl 2024-02-12 09:42:41 +00:00
Oli Scherer 0eee945680 Make `is_intrinsic` query return the intrinsic name 2024-02-12 09:33:52 +00:00
Ralf Jung 5fa69deb00 fix cycle error when a static and a promoted are mutually recursive
This also now allows promoteds everywhere to point to 'extern static', because why not?
We still check that constants cannot transitively reach 'extern static' through references.
(We allow it through raw pointers.)
2024-02-12 09:48:14 +01:00
Nicholas Nethercote 1f39c8b08f Change level used in `print_error_count`.
From `Fatal` to `Error`. It has no functional effect, but `Error` makes
more sense and lines up better with the `Warning` level used just above.
2024-02-12 18:39:20 +11:00
Nicholas Nethercote d4b77f64e4 Tweak delayed bug mentions.
Now that we have both `delayed_bug` and `span_delayed_bug`, it makes
sense to use the generic term "delayed bug" more.
2024-02-12 18:39:20 +11:00
Nicholas Nethercote e0a0cc2971 Remove `dcx` arg from `ReportErrorExt::add_args`.
Because it also has a `DiagnosticBuilder` arg, which contains a `dcx`
reference.

Also rename some `builder` variables as `diag`, because that's the usual
name.
2024-02-12 18:39:18 +11:00
Nicholas Nethercote 30774b0061 Remove final unwanted `unchecked_error_guaranteed` calls.
Now that error counts can't go up and down due to stashing/stealing, we
have a nice property:

  (err_count > 0) iff (an ErrorGuaranteed has been produced)

So we can now record `ErrorGuaranteed`s within `DiagCtxt` and use that
in methods like `has_error`, instead of checking that the count is
greater than 0 and calling `unchecked_error_guaranteed` to create the
`ErrorGuaranteed`.

In fact, we can record a `Vec<ErrorGuaranteed>` and use its length to
count the number, instead of maintaining a separate count.
2024-02-12 18:29:19 +11:00
bors aebf4511e9 Auto merge of #120835 - oli-obk:no_hir_coherence, r=cjgillot
Avoid accessing the HIR in the happy path of `coherent_trait`

Unfortunately the hir is still used in unsafety checks, and we do not have a way to avoid that. An impl's unsafety is not part of any query other than hir.

So this PR does not affect perf, but could still be considered a cleanup
2024-02-12 07:28:13 +00:00
Shoyu Vanilla 3856df059e Dejargnonize subst 2024-02-12 15:46:35 +09:00
bors de4d615e6b Auto merge of #120834 - oli-obk:only_local_coherence, r=lcnr
A trait's local impls are trivially coherent if there are no impls.

This avoids creating a dependency edge on the hir or the specialization graph

This may resolve part of the performance issue of https://github.com/rust-lang/rust/pull/120558
2024-02-12 05:05:57 +00:00
Frank King 0dbd6e9572 Improve some codes according to the reviews
- improve diagnostics of field uniqueness check and representation check
- simplify the implementation of field uniqueness check
- remove some useless codes and improvement neatness
2024-02-12 12:47:32 +08:00
Frank King 2b04ca94bb Add `#[derive(Clone, Copy)]` to anonymous adts
Fix the `AssertBoundIsClone` error for anonymous adts.
2024-02-12 12:47:32 +08:00
Frank King 7660d6bf2c Check representation of unnamed fields 2024-02-12 12:47:31 +08:00
Frank King 0c0df4efe0 Lowering field access for anonymous adts 2024-02-12 12:47:30 +08:00
Frank King 36d7e7fd3f check uniqueness of nested fields 2024-02-12 12:47:29 +08:00
Frank King 879a1e5713 Lower anonymous structs or unions to HIR 2024-02-12 12:47:23 +08:00
OdenShirataki 4ac90e286b Fix suggestion span for ?Sized
when param type has default
and type in trait is generic.
2024-02-12 11:33:11 +09:00
yukang 2bcbc16caf remove a bunch of dead parameters in fn 2024-02-12 09:51:35 +08:00
bors 084ce5bdb5 Auto merge of #120951 - matthiaskrgr:rollup-0nnm7dv, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #110483 (Create try_new function for ThinBox)
 - #120740 (Make cmath.rs a single file)
 - #120872 (hir: Refactor getters for HIR parents)
 - #120880 (add note on comparing vtables / function pointers)
 - #120885 (interpret/visitor: ensure we only see normalized types)
 - #120888 (assert_unsafe_precondition cleanup)
 - #120897 (Encode `coroutine_for_closure` for foreign crates)
 - #120937 ([docs] Update armv6k-nintendo-3ds platform docs for outdated info)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-12 00:34:22 +00:00
Matthias Krüger aeafbbeded
Rollup merge of #120897 - compiler-errors:foreign-async-closure, r=oli-obk
Encode `coroutine_for_closure` for foreign crates

Async closures (and "coroutine closures" in general) need to have their child coroutine encoded. This PR does that.

r? oli-obk
2024-02-11 23:19:10 +01:00
Matthias Krüger 90b4e4116f
Rollup merge of #120885 - RalfJung:normal-visitor, r=compiler-errors
interpret/visitor: ensure we only see normalized types

[Prior discussion on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/Normalization.20after.20field.20projection)
r? `@compiler-errors`
2024-02-11 23:19:09 +01:00
Matthias Krüger 4c154a1a48
Rollup merge of #120872 - petrochenkov:opthirpar, r=cjgillot
hir: Refactor getters for HIR parents

See individual commits.

I ended up removing on of the FIXMEs from https://github.com/rust-lang/rust/pull/120206 instead of addressing it.
2024-02-11 23:19:08 +01:00
Nicholas Nethercote b7b6ebca0c Fix inconsistencies in the diagnostic API methods.
- Remove low-value comments about functionality that is obvious.

- Add missing `track_caller` attributes -- every method should have one.

- Adjust `rustc_lint_diagnostic` attributes. Every method involving a
  `impl Into<DiagnosticMessage>` or `impl Into<SubdiangnosticMessage>`
  argument should have one, except for those producing bugs, which
  aren't user-facing.
2024-02-12 09:16:48 +11:00
Nicholas Nethercote c35983a748 Reorder the diagnostic API methods.
The current order is almost perfectly random. This commit puts them into
a predictable order in their own impl block, going from the highest
level (`Block`) to the lowest (`Expect`). Within each level this is the
order:

- struct_err, err
- struct_span_err, span_err
- create_err, emit_err

The first one in each pair creates a diagnostic, the second one creates
*and* emits a diagnostic. Not every method is present for every level.

The diff is messy, but other than moving methods around, the only thing
it does is create the new `impl DiagCtxt` block with its own comment.
2024-02-12 09:16:45 +11:00
bors 520b0b20aa Auto merge of #120619 - compiler-errors:param, r=lcnr
Assert that params with the same *index* have the same *name*

Found this bug when trying to build libcore with the new solver, since it will canonicalize two params with the same index into *different* placeholders if those params differ by name.
2024-02-11 22:13:52 +00:00
Michael Goulet 87816378ab Fix async closures in CTFE 2024-02-11 22:09:52 +00:00
Michael Goulet cb024ba6e3 is_closure_like 2024-02-11 22:09:52 +00:00
Michael Goulet 9789e88cfe Check that the ABI of the instance we are inlining is correct 2024-02-11 19:17:42 +00:00
Michael Goulet 38df5bdcf1 Ignore own item bounds in parent alias types in `for_each_item_bound` 2024-02-11 18:23:05 +00:00
bors a166af7729 Auto merge of #120903 - matthiaskrgr:rollup-tmsuzth, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #119213 (simd intrinsics: add simd_shuffle_generic and other missing intrinsics)
 - #120272 (Suppress suggestions in derive macro)
 - #120773 (large_assignments: Allow moves into functions)
 - #120874 (Take empty `where` bounds into account when suggesting predicates)
 - #120882 (interpret/write_discriminant: when encoding niched variant, ensure the stored value matches)
 - #120883 (interpret: rename ReadExternStatic → ExternStatic)
 - #120890 (Adapt `llvm-has-rust-patches` validation to take `llvm-config` into account.)
 - #120895 (don't skip coercions for types with errors)
 - #120896 (Print kind of coroutine closure)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-11 17:43:51 +00:00
Ralf Jung e13de311d5 make Primary/Secondary importance consistent between CellBorrow and MutBorrow 2024-02-11 15:12:10 +01:00
Ralf Jung d5de9a6105 check_consts: fix some duplicate errors by not calling check_static unnecessarily 2024-02-11 15:12:10 +01:00
bors 9aa232ecc7 Auto merge of #120405 - cjgillot:gvn-pointer, r=oli-obk
Fold pointer operations in GVN

This PR proposes 2 combinations of cast operations in MIR GVN:
- a chain of `PtrToPtr` or `MutToConstPointer` casts can be folded together into a single `PtrToPtr` cast;
- we attempt to evaluate more ptr ops when there is no provenance.

In particular, this allows to read from static slices.

This is not yet sufficient to see through slice operations that use `PtrComponents` (because that's a union), but still a step forward.

r? `@ghost`
2024-02-11 04:24:40 +00:00
Matthias Krüger 870435b50b
Rollup merge of #120896 - compiler-errors:coro-closure-kind, r=oli-obk
Print kind of coroutine closure

Make sure that we print "async closure" when we have an async closure, rather than calling it generically a ["coroutine-closure"](https://github.com/rust-lang/rust/pull/120361).

Fixes #120886

r? oli-obk
2024-02-11 01:37:57 +01:00
Matthias Krüger 302301bc3a
Rollup merge of #120895 - lukas-code:error-coercions-ice, r=compiler-errors
don't skip coercions for types with errors

fixes https://github.com/rust-lang/rust/issues/120884
2024-02-11 01:37:57 +01:00
Matthias Krüger 09bbcd6667
Rollup merge of #120883 - RalfJung:extern-static-err, r=oli-obk
interpret: rename ReadExternStatic → ExternStatic

This error shows up for reads and writes, so `ReadExternStatic` is misleading.
2024-02-11 01:37:56 +01:00
Matthias Krüger e82e087582
Rollup merge of #120882 - RalfJung:set-discriminant, r=compiler-errors
interpret/write_discriminant: when encoding niched variant, ensure the stored value matches

Cc https://github.com/rust-lang/unsafe-code-guidelines/issues/487
2024-02-11 01:37:55 +01:00
Matthias Krüger 0171057e66
Rollup merge of #120874 - gurry:120838-extra-where-in-suggestion, r=fmease
Take empty `where` bounds into account when suggesting predicates

Fixes #120838
2024-02-11 01:37:55 +01:00
Matthias Krüger fd287d2e88
Rollup merge of #120773 - Enselic:copy-vs-move, r=oli-obk
large_assignments: Allow moves into functions

Moves into functions are typically implemented with pointer passing
rather than memcpy's at the llvm-ir level, so allow moves into
functions.

Part of the "Differentiate between Operand::Move and Operand::Copy" step of https://github.com/rust-lang/rust/issues/83518.

r? `@oli-obk` (who I think is still E-mentor?)
2024-02-11 01:37:55 +01:00
Matthias Krüger e525bc9592
Rollup merge of #120272 - long-long-float:suppress-suggestions-in-derive-macro, r=oli-obk
Suppress suggestions in derive macro

close #118809

I suppress warnings inside derive macros.

For example, the compiler emits following error by a program described in https://github.com/rust-lang/rust/issues/118809#issuecomment-1852256687 with a suggestion that indicates invalid syntax.

```
error[E0308]: `?` operator has incompatible types
 --> src/main.rs:3:17
  |
3 | #[derive(Debug, Deserialize)]
  |                 ^^^^^^^^^^^ expected `u32`, found `u64`
  |
  = note: `?` operator cannot convert from `u64` to `u32`
  = note: this error originates in the derive macro `Deserialize` (in Nightly builds, run with -Z macro-backtrace for more info)
help: you can convert a `u64` to a `u32` and panic if the converted value doesn't fit
  |
3 | #[derive(Debug, Deserialize.try_into().unwrap())]
  |                            ++++++++++++++++++++

For more information about this error, try `rustc --explain E0308`.
error: could not compile `serde_test` (bin "serde_test") due to 2 previous errors
```

In this PR, suggestions to cast are suppressed.

```
error[E0308]: `?` operator has incompatible types
 --> src/main.rs:3:17
  |
3 | #[derive(Debug, Deserialize)]
  |                 ^^^^^^^^^^^ expected `u32`, found `u64`
  |
  = note: `?` operator cannot convert from `u64` to `u32`
  = note: this error originates in the derive macro `Deserialize` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0308`.
error: could not compile `serde_test` (bin "serde_test") due to 2 previous errors
```
2024-02-11 01:37:54 +01:00
Michael Goulet 5461fd4250 Gracefully handle non-WF alias in assemble_alias_bound_candidates_recur 2024-02-10 23:49:21 +00:00
Michael Goulet 86ddb53cab Print kind of coroutine closure 2024-02-10 23:18:01 +00:00
Michael Goulet c210fec3cb Encode coroutine_for_closure for foreign crates 2024-02-10 22:58:26 +00:00
bors 42752cbe09 Auto merge of #117206 - cjgillot:jump-threading-default, r=tmiasko
Enable MIR JumpThreading by default

Mostly for perf

r? `@ghost`
2024-02-10 22:15:18 +00:00
Lukas Markeffsky e330fe9c21 don't skip coercions for types with errors 2024-02-10 23:13:47 +01:00
long-long-float 1e59e66225 Fix to use for loop 2024-02-11 02:43:55 +09:00
Ralf Jung 29db7890ba interpret/visitor: ensure we only see normalized types 2024-02-10 17:00:24 +01:00
Martin Nordholts e2979a8b8c large_assignments: Allow moves into functions
Moves into functions are typically implemented with pointer passing
rather than memcpy's at the llvm-ir level, so allow moves into
functions.
2024-02-10 16:17:00 +01:00
Ralf Jung 77f8c3caea detect consts that reference extern statics 2024-02-10 16:13:48 +01:00
Ralf Jung 9c0623fe8f validation: descend from consts into statics 2024-02-10 16:13:47 +01:00
Ralf Jung 4e77e368eb unstably allow constants to refer to statics and read from immutable statics 2024-02-10 16:12:55 +01:00
Ralf Jung d56f3b6a5d interpret: rename ReadExternStatic → ExternStatic 2024-02-10 16:06:02 +01:00
Ralf Jung 18ed966ab5 interpret/write_discriminant: when encoding niched variant, ensure the stored value matches 2024-02-10 15:33:58 +01:00
Matthias Krüger 55913368c5
Rollup merge of #120870 - Zalathar:allow-min-spec, r=oli-obk
Allow restricted trait impls under `#[allow_internal_unstable(min_specialization)]`

This is a follow-up to #119963 and a companion to #120866, though it can land independently from the latter.

---

We have several compiler crates that only enable `#[feature(min_specialization)]` because it is required by their expansions of `newtype_index!`, in order to implement traits marked with `#[rustc_specialization_trait]`.

This PR allows those traits to be implemented internally by macros with `#[allow_internal_unstable(min_specialization)]`, without needing specialization to be enabled in the enclosing crate.
2024-02-10 13:12:31 +01:00
Matthias Krüger ed3b049a8b
Rollup merge of #120866 - Zalathar:no-min-spec, r=compiler-errors
Remove unnecessary `#![feature(min_specialization)]`

As of #119963 and #120676, we can now rely on `newtype_index!` having `#[allow_internal_unstable(min_specialization)]`, so there are a few compiler crates that no longer need to include min-spec in their own crate features.

---

Some of the expansions of `newtype_index!` still appear to require min-spec in the crate features. I think this is because `#[orderable]` causes the expansion to include an implementation of `TrustedStep`, which is flagged with `#[rustc_specialization_trait]`, and for whatever reason that isn't permitted by allow-internal-unstable. So this PR only touches the crates where that isn't the case.
2024-02-10 13:12:31 +01:00
Matthias Krüger 9a8958f2bb
Rollup merge of #120865 - saethlin:missing-o-files, r=nnethercote
Turn the "no saved object file in work product" ICE into a translatable fatal error

I don't know if it's fair to say this fixes https://github.com/rust-lang/rust/issues/120854 but it surely makes the error reporting better and should encourage people with good instincts like ```@CinchBlue.```
2024-02-10 13:12:31 +01:00
Matthias Krüger 2dbc9f55f7
Rollup merge of #120859 - nnethercote:fix-120856, r=oli-obk
Loosen an assertion to account for stashed errors.

The meaning of this assertion changed in #120828 when the meaning of `has_errors` changed to exclude stashed errors. Evidently the new meaning is too restrictive.

Fixes #120856.

r? ```@oli-obk```
2024-02-10 13:12:30 +01:00
Matthias Krüger e11e4446da
Rollup merge of #120719 - compiler-errors:no-dyn-atb, r=lcnr
Remove support for `associated_type_bound` nested in `dyn` types

These necessarily desugar to `impl Trait`, which is inconsistent with the `associated_type_bound` feature after #120584.

This PR keeps the `is_in_dyn_type` hack, which kind of makes me sad. Ideally, we'd be validating that no object types have associated type bounds somewhere else. Unfortunately, we can't do this later during astconv (i think?), nor can we do it earlier during ast validation (i think?) because of the feature gating of ATB being a *warning* rather than an *error*. Let me know if you have thoughts about this.

r? lcnr
2024-02-10 13:12:28 +01:00
Matthias Krüger 0b7f0ff230
Rollup merge of #117614 - RalfJung:static-mut-refs, r=davidtwco,oli-obk
static mut: allow mutable reference to arbitrary types, not just slices and arrays

For historical reasons, we allow this:
```rust
static mut ARRAY: &'static mut [isize] = &mut [1];
```
However, we do not allow this:
```rust
static mut INT: &'static mut isize = &mut 1;
```

I think that's terribly inconsistent. I don't care much for `static mut`, but we have to keep it around for backwards compatibility and so we have to keep supporting it properly in the compiler. In recent refactors of how we deal with mutability of data in `static` and `const`, I almost made a fatal mistake since I tested `static mut INT: &'static mut isize = &mut 1` and concluded that we don't allow such `'static` mutable references even inside `static mut`. After all, nobody would expect this to be allowed only for arrays and slices, right?!?? So for the sake of our own sanity, and of whoever else reverse engineers these rules in the future to understand what the Rust compiler accepts or does not accept, I propose that we accept this for all types, not just arrays and slices.
2024-02-10 13:12:28 +01:00
Gurinder Singh 0815067796 Take empty `where` into account when suggesting predicates 2024-02-10 16:05:39 +05:30
bors 232919c33a Auto merge of #120771 - oli-obk:useless_non_ensure_query_call, r=davidtwco
Use `ensure` when the result of the query is not needed beyond its `Result`ness

while I would like to just remove the `tcx` methods for ensure-only queries, that is hard to do without another query annotation or by turning the `define_callbacks` macro into a proc macro to get more control

should fix perf regression of https://github.com/rust-lang/rust/pull/120558
2024-02-10 09:27:14 +00:00
Vadim Petrochenkov b07283815b hir: Remove `hir::Map::{opt_parent_id,parent_id,get_parent,find_parent}` 2024-02-10 12:24:46 +03:00
Vadim Petrochenkov e46e3e7107 hir: Introduce `TyCtxt::parent_hir_{id,node}`
Remove the FIXME and keep `CRATE_HIR_ID` being its own parent.
This scheme turned out to be more practical than having an `Option` on closer inspection.

Also make `hir_owner_parent` more readable.
2024-02-10 12:23:11 +03:00
bors 757b8efed4 Auto merge of #120712 - compiler-errors:async-closures-harmonize, r=oli-obk
Harmonize `AsyncFn` implementations, make async closures conditionally impl `Fn*` traits

This PR implements several changes to the built-in and libcore-provided implementations of `Fn*` and `AsyncFn*` to address two problems:
1. async closures do not implement the `Fn*` family traits, leading to breakage: https://crater-reports.s3.amazonaws.com/pr-120361/index.html
2. *references* to async closures do not implement `AsyncFn*`, as a consequence of the existing blanket impls of the shape `AsyncFn for F where F: Fn, F::Output: Future`.

In order to fix (1.), we implement `Fn` traits appropriately for async closures. It turns out that async closures can:
* always implement `FnOnce`, meaning that they're drop-in compatible with `FnOnce`-bound combinators like `Option::map`.
* conditionally implement `Fn`/`FnMut` if they have no captures, which means that existing usages of async closures should *probably* work without breakage (crater checking this: https://github.com/rust-lang/rust/pull/120712#issuecomment-1930587805).

In order to fix (2.), we make all of the built-in callables implement `AsyncFn*` via built-in impls, and instead adjust the blanket impls for `AsyncFn*` provided by libcore to match the blanket impls for `Fn*`.
2024-02-10 07:15:15 +00:00
Zalathar a2479a4ae7 Remove unnecessary `min_specialization` after bootstrap
These crates all needed specialization for `newtype_index!`, which will no
longer be necessary when the current nightly eventually becomes the next
bootstrap compiler.
2024-02-10 18:15:11 +11:00
Zalathar 7b73e4fd44 Allow restricted trait impls in macros with `min_specialization`
Implementing traits marked with `#[rustc_specialization_trait]` normally
requires (min-)specialization to be enabled for the enclosing crate.

With this change, that permission can also be granted by an
`allow_internal_unstable` attribute on the macro that generates the impl.
2024-02-10 18:14:02 +11:00
trevyn 29fd82b24e Be less confident when `dyn` suggestion is not checked for object safety 2024-02-09 20:47:50 -08:00
Michael Goulet e6f5af9671 Remove unused fn 2024-02-10 03:52:13 +00:00
Michael Goulet fde695a2d1 Add a helpful suggestion 2024-02-10 03:31:34 +00:00
Michael Goulet 973bbfbd23 No more associated type bounds in dyn trait 2024-02-10 03:23:51 +00:00
Zalathar cf1096eb72 Remove unnecessary `#![feature(min_specialization)]` 2024-02-10 12:26:14 +11:00
Ben Kimock 3d4a9f5047 Turn the "no saved object file in work product" ICE into a translatable fatal error 2024-02-09 20:22:15 -05:00
Matthias Krüger 8e1eaddd27
Rollup merge of #120853 - blyxyas:no-collect, r=cjgillot
Avoid a collection and iteration on empty passes

Just some mini optimization I saw in the wild. This way, we avoid a `collect` and `map` on an empty `passes`. Honestly, I don't even think this is big enough of a change to make a benchmark, but I'd still like to see results.

Based on [this book](https://nnethercote.github.io/perf-book/iterators.html#collect-and-extend)
2024-02-10 00:58:40 +01:00
Matthias Krüger 8177c0fead
Rollup merge of #120850 - petrochenkov:empimpres, r=cjgillot
ast_lowering: Fix regression in `use ::{}` imports.

Fixes https://github.com/rust-lang/rust/issues/120789
2024-02-10 00:58:39 +01:00
Matthias Krüger 317c372284
Rollup merge of #120846 - petrochenkov:jobs, r=oli-obk
Update jobserver-rs to 0.1.28

Fixes the issues found in https://github.com/rust-lang/rust/issues/120515 besides the diagnostic wording.
2024-02-10 00:58:38 +01:00
Matthias Krüger 9ec287dec2
Rollup merge of #120584 - compiler-errors:u, r=lcnr
For a rigid projection, recursively look at the self type's item bounds to fix the `associated_type_bounds` feature

Given a deeply nested rigid projection like `<<<T as Trait1>::Assoc1 as Trait2>::Assoc2 as Trait3>::Assoc3`, this PR adjusts both trait solvers to look at the item bounds for all of `Assoc3`, `Assoc2`, and `Assoc1` in order to satisfy a goal. We do this because the item bounds for projections may contain relevant bounds for *other* nested projections when the `associated_type_bounds` (ATB) feature is enabled. For example:

```rust
#![feature(associated_type_bounds)]

trait Trait1 {
    type Assoc1: Trait2<Assoc2: Foo>;
    // Item bounds for `Assoc1` are:
    // `<Self as Trait1>::Assoc1: Trait2`
    // `<<Self as Trait1>::Assoc1 as Trait2>::Assoc2: Foo`
}

trait Trait2 {
    type Assoc2;
}

trait Foo {}

fn hello<T: Trait1>(x: <<T as Trait1>::Assoc1 as Trait2>::Assoc2) {
    fn is_foo(_: impl Foo) {}
    is_foo(x);
    // Currently fails with:
    // ERROR the trait bound `<<Self as Trait1>::Assoc1 as Trait2>::Assoc2: Foo` is not satisfied
}
```

This has been a long-standing place of brokenness for ATBs, and is also part of the reason why ATBs currently desugar so differently in various positions (i.e. sometimes desugaring to param-env bounds, sometimes desugaring to RPITs, etc). For example, in RPIT and TAIT position, `impl Foo<Bar: Baz>` currently desugars to `impl Foo<Bar = impl Baz>` because we do not currently take advantage of these nested item bounds if we desugared them into a single set of item bounds on the opaque. This is obviously both strange and unnecessary if we just take advantage of these bounds as we should.

## Approach

This PR repeatedly peels off each projection of a given goal's self type and tries to match its item bounds against a goal, repeating with the self type of the projection. This is pretty straightforward to implement in the new solver, only requiring us to loop on the self type of a rigid projection to discover inner rigid projections, and we also need to introduce an extra probe so we can normalize them.

In the old solver, we can do essentially the same thing, however we rely on the fact that projections *should* be normalized already. This is obviously not always the case -- however, in the case that they are not fully normalized, such as a projection which has both infer vars and, we bail out with ambiguity if we hit an infer var for the self type.

## Caveats

⚠️ In the old solver, this has the side-effect of actually stalling some higher-ranked trait goals of the form `for<'a> <?0 as Tr<'a>>: Tr2`. Because we stall them, they no longer are eagerly treated as error -- this cause some existing `known-bug` tests to go from fail -> pass.

I'm pretty unconvinced that this is a problem since we make code that we expect to pass in the *new* solver also pass in the *old* solver, though this obviously doesn't solve the *full* problem.

## And then also...

We also adjust the desugaring of ATB to always desugar to a regular associated bound, rather than sometimes to an impl Trait **except** for when the ATB is present in a `dyn Trait`. We need to lower `dyn Trait<Assoc: Bar>` to `dyn Trait<Assoc = impl Bar>` because object types need all of their associated types specified.

I would also be in favor of splitting out the ATB feature and/or removing support for object types in order to stabilize just the set of positions for which the ATB feature is consistent (i.e. always elaborates to a bound).
2024-02-10 00:58:36 +01:00
Nicholas Nethercote bb60ded24b Loosen an assertion to account for stashed errors.
The meaning of this assertion changed in #120828 when the meaning of
`has_errors` changed to exclude stashed errors. Evidently the new
meaning is too restrictive.

Fixes #120856.
2024-02-10 09:14:59 +11:00
Camille GILLOT 014b29eecf Remove ConstGoto and SeparateConstSwitch. 2024-02-09 21:13:53 +00:00
Camille GILLOT e132cac3c4 Enable by default. 2024-02-09 21:13:51 +00:00
Camille GILLOT 7a6b00e786 Remove untested arithmetic ops. 2024-02-09 21:06:25 +00:00
Camille GILLOT d50f26e409 Const-prop pointers. 2024-02-09 21:06:23 +00:00
bors d44e3b95cb Auto merge of #120852 - matthiaskrgr:rollup-01pr8gj, r=matthiaskrgr
Rollup of 11 pull requests

Successful merges:

 - #120351 (Implement SystemTime for UEFI)
 - #120354 (improve normalization of `Pointee::Metadata`)
 - #120776 (Move path implementations into `sys`)
 - #120790 (better error message on download CI LLVM failure)
 - #120806 (Clippy subtree update)
 - #120815 (Improve `Option::inspect` docs)
 - #120822 (Emit more specific diagnostics when enums fail to cast with `as`)
 - #120827 (Print image input file and checksum in CI only)
 - #120836 (hide impls if trait bound is proven from env)
 - #120844 (Build DebugInfo for async closures)
 - #120851 (Remove duplicate release note)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-09 21:06:12 +00:00
Camille GILLOT 5a6f14c4f4 Split gvn wide ptr tests. 2024-02-09 21:01:57 +00:00
Camille GILLOT 28df0a62f6 Compute binary ops between pointers in GVN. 2024-02-09 21:01:57 +00:00
Camille GILLOT 304b4ad8b9 Compute unsizing casts in GVN. 2024-02-09 21:01:57 +00:00
Camille GILLOT 1f544ca0cc Fold consecutive PtrToPtr casts. 2024-02-09 21:01:56 +00:00
Oli Scherer 614ff0fae9 Don't reinvoke `impl_trait_ref` query after it was already invoked 2024-02-09 20:33:23 +00:00
Oli Scherer 97b4b7f72b use `impl Trait` argument instead of generic param for simplicity 2024-02-09 20:25:18 +00:00
Oli Scherer 7f871ab9aa No need for FnMut when FnOnce works now 2024-02-09 20:23:40 +00:00
Oli Scherer 23277a502e Simplify conditional erroring 2024-02-09 20:23:18 +00:00
Oli Scherer 4661c83530 Avoid accessing the HIR in the happy path of `coherent_trait` 2024-02-09 20:12:02 +00:00
blyxyas 4ef1790b4e
tidy 2024-02-09 19:30:47 +01:00
Matthias Krüger aa0b0b65b3
Rollup merge of #120844 - compiler-errors:async-di, r=oli-obk
Build DebugInfo for async closures

The test is pretty bare, because I don't really know how to write debuginfo tests. I'd like to land this first, and then flesh it out correctly one it's no longer ICEing on master (which breaks people's ability to test using async closures).

r? oli-obk cc `@rust-lang/wg-debugging` (if any of y'all want to help me write a more fleshed out async closures test)
2024-02-09 19:21:19 +01:00
Matthias Krüger 251584581f
Rollup merge of #120836 - lcnr:param-env-hide-impl, r=BoxyUwU
hide impls if trait bound is proven from env

AVERT YOUR EYES `@compiler-errors`

fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/76 and https://github.com/rust-lang/trait-system-refactor-initiative/issues/12#issuecomment-1865234925

this is kinda ugly and I hate it, but I wasn't able to think of a cleaner approach for now. I am also unsure whether we have to refine this filtering later on, so by making the change pretty minimal it should be easier to improve going forward.

r? `@BoxyUwU`
2024-02-09 19:21:19 +01:00
Matthias Krüger d9a957b32a
Rollup merge of #120822 - gurry:120756-terse-non-prim-cast-diag, r=petrochenkov
Emit more specific diagnostics when enums fail to cast with `as`

Fixes #120756

Changes this diagnostic reported in the issue:
```
error[E0605]: non-primitive cast: `Bad` as `u32`
  --> src/main.rs:18:10
   |
18 |     dbg!(bad as u32);
   |          ^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
```

to this:
```
error[E0605]: non-primitive cast: `Bad` as `u32`
  --> src/main.rs:18:10
   |
18 |     dbg!(bad as u32);
   |          ^^^^^^^^^^ an `as` expression can be used to convert enum types to numeric types only if the enum type is unit-only or field-less
   |
   = note: see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information
```

This change is only for enums. The diagnostic remains unchanged for all other cases.
2024-02-09 19:21:18 +01:00
Matthias Krüger 99bafad6c2
Rollup merge of #120354 - lukas-code:metadata-normalize, r=lcnr
improve normalization of `Pointee::Metadata`

This PR makes it so that `<Wrapper<Tail> as Pointee>::Metadata` is normalized to `<Tail as Pointee>::Metadata` if we don't know `Wrapper<Tail>: Sized`. With that, the trait solver can prove projection predicates like `<Wrapper<Tail> as Pointee>::Metadata == <Tail as Pointee>::Metadata`, which makes it possible to use the metadata APIs to cast between the tail and the wrapper:

```rust
#![feature(ptr_metadata)]

use std::ptr::{self, Pointee};

fn cast_same_meta<T: ?Sized, U: ?Sized>(ptr: *const T) -> *const U
where
    T: Pointee<Metadata = <U as Pointee>::Metadata>,
{
    let (thin, meta) = ptr.to_raw_parts();
    ptr::from_raw_parts(thin, meta)
}

struct Wrapper<T: ?Sized>(T);

fn cast_to_wrapper<T: ?Sized>(ptr: *const T) -> *const Wrapper<T> {
    cast_same_meta(ptr)
}
```

Previously, this failed to compile:

```
error[E0271]: type mismatch resolving `<Wrapper<T> as Pointee>::Metadata == <T as Pointee>::Metadata`
  --> src/lib.rs:16:5
   |
15 | fn cast_to_wrapper<T: ?Sized>(ptr: *const T) -> *const Wrapper<T> {
   |                    - found this type parameter
16 |     cast_same_meta(ptr)
   |     ^^^^^^^^^^^^^^ expected `Wrapper<T>`, found type parameter `T`
   |
   = note: expected associated type `<Wrapper<T> as Pointee>::Metadata`
              found associated type `<T as Pointee>::Metadata`
   = note: an associated type was expected, but a different one was found
```

(Yes, you can already do this with `as` casts. But using functions is so much  *safer* , because you can't change the metadata on accident.)

---

This PR essentially changes the built-in impls of `Pointee` from this:

```rust
// before

impl Pointee for u8 {
    type Metadata = ();
}

impl Pointee for [u8] {
    type Metadata = usize;
}

// ...

impl Pointee for Wrapper<u8> {
    type Metadata = ();
}

impl Pointee for Wrapper<[u8]> {
    type Metadata = usize;
}

// ...

// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T: ?Sized> Pointee for Wrapper<T>
where
    Wrapper<T>: Sized
{
    type Metadata = ();
}

// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T /*: Sized */> Pointee for T {
    type Metadata = ();
}
```

to this:

```rust
// after

impl Pointee for u8 {
    type Metadata = ();
}

impl Pointee for [u8] {
    type Metadata = usize;
}

// ...

impl<T: ?Sized> Pointee for Wrapper<T> {
    // in the old solver this will instead project to the "deep" tail directly,
    // e.g. `Wrapper<Wrapper<T>>::Metadata = T::Metadata`
    type Metadata = <T as Pointee>::Metadata;
}

// ...

// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T /*: Sized */> Pointee for T {
    type Metadata = ();
}
```
2024-02-09 19:21:16 +01:00
blyxyas e59d9b171e
Avoid a collection and iteration on empty passes 2024-02-09 19:15:40 +01:00
bors f4cfd87202 Auto merge of #120676 - Mark-Simulacrum:bootstrap-bump, r=clubby789
Bump bootstrap compiler to just-built 1.77 beta

https://forge.rust-lang.org/release/process.html#master-bootstrap-update-t-2-day-tuesday
2024-02-09 18:09:02 +00:00
Vadim Petrochenkov 8b6b9c5efc ast_lowering: Fix regression in `use ::{}` imports. 2024-02-09 20:17:48 +03:00
Vadim Petrochenkov 83f3bc4271 Update jobserver-rs to 0.1.28 2024-02-09 19:13:07 +03:00
Michael Goulet 34ed554d81 Build DebugInfo for coroutine-closure 2024-02-09 16:01:29 +00:00
bors e28fae52d9 Auto merge of #120843 - matthiaskrgr:rollup-med37z5, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #113671 (Make privacy visitor use types more (instead of HIR))
 - #120308 (core/time: avoid divisions in Duration::new)
 - #120693 (Invert diagnostic lints.)
 - #120704 (A drive-by rewrite of `give_region_a_name()`)
 - #120809 (Use `transmute_unchecked` in `NonZero::new`.)
 - #120817 (Fix more `ty::Error` ICEs in MIR passes)
 - #120828 (Fix `ErrorGuaranteed` unsoundness with stash/steal.)
 - #120831 (Startup objects disappearing from sysroot)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-09 15:34:48 +00:00
Matthias Krüger 2f1ac412ec
Rollup merge of #120828 - nnethercote:fix-stash-steal, r=oli-obk
Fix `ErrorGuaranteed` unsoundness with stash/steal.

When you stash an error, the error count is incremented. You can then use the non-zero error count to get an `ErrorGuaranteed`. You can then steal the error, which decrements the error count. You can then cancel the error.

Example code:
```
fn unsound(dcx: &DiagCtxt) -> ErrorGuaranteed {
    let sp = rustc_span::DUMMY_SP;
    let k = rustc_errors::StashKey::Cycle;
    dcx.struct_err("bogus").stash(sp, k);           // increment error count on stash
    let guar = dcx.has_errors().unwrap();           // ErrorGuaranteed from error count > 0
    let err = dcx.steal_diagnostic(sp, k).unwrap(); // decrement error count on steal
    err.cancel();                                   // cancel error
    guar                                            // ErrorGuaranteed with no error emitted!
}
```

This commit fixes the problem in the simplest way: by not counting stashed errors in `DiagCtxt::{err_count,has_errors}`.

However, just doing this without any other changes leads to over 40 ui test failures. Mostly because of uninteresting extra errors (many saying "type annotations needed" when type inference fails), and in a few cases, due to delayed bugs causing ICEs when no normal errors are printed.

To fix these, this commit adds `DiagCtxt::stashed_err_count`, and uses it in three places alongside `DiagCtxt::{has_errors,err_count}`. It's dodgy to rely on it, because unlike `DiagCtxt::err_count` it can go up and down. But it's needed to preserve existing behaviour, and at least the three places that need it are now obvious.

r? oli-obk
2024-02-09 14:41:52 +01:00
Matthias Krüger 116efb5bb1
Rollup merge of #120817 - compiler-errors:more-mir-errors, r=oli-obk
Fix more `ty::Error` ICEs in MIR passes

Fixes #120791 - Add a check for `ty::Error` in the `ByMove` coroutine pass
Fixes #120816 - Add a check for `ty::Error` in the MIR validator

Also a drive-by fix for a FIXME I had asked oli to add

r? oli-obk
2024-02-09 14:41:51 +01:00
Matthias Krüger df2281b058
Rollup merge of #120704 - amandasystems:silly-region-name-rewrite, r=compiler-errors
A drive-by rewrite of `give_region_a_name()`

This drive-by rewrite makes the cache-updating nature of the method clearer, using the Entry API into the hash table for region names to capture the update-insert nature of the method. May be marginally more efficient since it only runtime-borrows and indexes the map once, but in this context the performance impact is almost certainly completely negligible.

Note that this commit should preserve all externally visible behaviour. Notably, it preserves the debug logging:

1. printing even in the case of a `None` for the new computed name, and
2. only printing on new values, begin silent on reused values
2024-02-09 14:41:50 +01:00
Matthias Krüger 46a0448405
Rollup merge of #120693 - nnethercote:invert-diagnostic-lints, r=davidtwco
Invert diagnostic lints.

That is, change `diagnostic_outside_of_impl` and `untranslatable_diagnostic` from `allow` to `deny`, because more than half of the compiler has been converted to use translated diagnostics.

This commit removes more `deny` attributes than it adds `allow` attributes, which proves that this change is warranted.

r? ````@davidtwco````
2024-02-09 14:41:50 +01:00
Matthias Krüger f41d0d90c2
Rollup merge of #113671 - oli-obk:normalize_weak_tys, r=petrochenkov
Make privacy visitor use types more (instead of HIR)

r? ``@petrochenkov``

This is a prerequisite to normalizing projections, as otherwise we have too many invalid bound vars (hir_ty_to_ty is creating types that have bound vars, but no binder).

The commits are still chaotic, I'm gonna clean them up, but I just wanted to let you know about the general direction and wondering if we could land this before adding normalization, as normalization is where behavioral changes happen, and I'd like to keep that part as minimal as possible.

[context can be found on zulip](https://rust-lang.zulipchat.com/#narrow/stream/315482-t-compiler.2Fetc.2Fopaque-types/topic/weak.20type.20aliases.20and.20privacy)
2024-02-09 14:41:48 +01:00
bors 8fb67fb37f Auto merge of #120594 - saethlin:delayed-debug-asserts, r=oli-obk
Toggle assert_unsafe_precondition in codegen instead of expansion

The goal of this PR is to make some of the unsafe precondition checks in the standard library available in debug builds. Some UI tests are included to verify that it does that.

The diff is large, but most of it is blessing mir-opt tests and I've also split up this PR so it can be reviewed commit-by-commit.

This PR:
1. Adds a new intrinsic, `debug_assertions` which is lowered to a new MIR NullOp, and only to a constant after monomorphization
2. Rewrites `assume_unsafe_precondition` to check the new intrinsic, and be monomorphic.
3. Skips codegen of the `assume` intrinsic in unoptimized builds, because that was silly before but with these checks it's *very* silly
4. The checks with the most overhead are `ptr::read`/`ptr::write` and `NonNull::new_unchecked`. I've simply added `#[cfg(debug_assertions)]` to the checks for `ptr::read`/`ptr::write` because I was unable to come up with any (good) ideas for decreasing their impact. But for `NonNull::new_unchecked` I found that the majority of callers can use a different function, often a safe one.

Yes, this PR slows down the compile time of some programs. But in our benchmark suite it's never more than 1% icount, and the average icount change in debug-full programs is 0.22%. I think that is acceptable for such an improvement in developer experience.

https://github.com/rust-lang/rust/issues/120539#issuecomment-1922687101
2024-02-09 13:33:38 +00:00
lcnr 5051637979 hide impls if trait bound is proven from env 2024-02-09 12:41:39 +01:00
lcnr a913c243da add comment 2024-02-09 10:44:19 +01:00
Oli Scherer e2349ea2e1 A trait's local impls are trivially coherent if there are no impls.
This avoids creating a dependency edge on the hir or the specialization graph
2024-02-09 09:33:56 +00:00
Gurinder Singh 6e37f955e5 Emit more specific diagnostics when enums fail to cast with `as` 2024-02-09 09:19:44 +05:30