about summary refs log tree commit diff
path: root/compiler/rustc_middle/src
AgeCommit message (Collapse)AuthorLines
2025-01-15Rollup merge of #135003 - RalfJung:deprecate-allowed-through-unstable, ↵Guillaume Gomez-9/+12
r=davidtwco deprecate `std::intrinsics::transmute` etc, use `std::mem::*` instead The `rustc_allowed_through_unstable_modules` attribute lets users call `std::mem::transmute` as `std::intrinsics::transmute`. The former is a reexport of the latter, and for a long time we didn't properly check stability for reexports, so making this a hard error now would be a breaking change for little gain. But at the same time, `std::intrinsics::transmute` is not the intended path for this function, so I think it is a good idea to show a deprecation warning when that path is used. This PR implements that, for all the functions in `std::intrinsics` that carry the attribute. I assume this will need ``@rust-lang/libs-api`` FCP.
2025-01-15Auto merge of #134353 - oli-obk:safe-target-feature-unsafe-by-default, ↵bors-1/+12
r=wesleywiser Treat safe target_feature functions as unsafe by default [less invasive variant] This unblocks * #134090 As I stated in https://github.com/rust-lang/rust/pull/134090#issuecomment-2541332415 I think the previous impl was too easy to get wrong, as by default it treated safe target feature functions as safe and had to add additional checks for when they weren't. Now the logic is inverted. By default they are unsafe and you have to explicitly handle safe target feature functions. This is the less (imo) invasive variant of #134317, as it doesn't require changing the Safety enum, so it only affects FnDefs and nothing else, as it should.
2025-01-15Render fn defs with target_features attrs with the attributeOli Scherer-1/+8
2025-01-15late_report_deprecation: move fast-path closer to the core logicRalf Jung-9/+12
2025-01-14Enforce syntactical stability of const traits in HIRMichael Goulet-2/+87
2025-01-14Auto merge of #135278 - tgross35:ignore-std-dep-crates, r=SparrowLiibors-0/+18
Exclude dependencies of `std` for diagnostics Currently crates in the sysroot can show up in diagnostic suggestions, such as in https://github.com/rust-lang/rust/issues/135232. To prevent this, duplicate `all_traits` into `visible_traits` which only shows traits in non-private crates. Setting `#![feature(rustc_private)]` overrides this and makes items in private crates visible as well, since `rustc_private` enables use of `std`'s private dependencies. This may be reviewed per-commit. Fixes: https://github.com/rust-lang/rust/issues/135232
2025-01-14Add hir::HeaderSafety to make follow up commits simplerOli Scherer-0/+4
2025-01-14Add `tcx.visible_traits()` and use it for producing diagnosticsTrevor Gross-0/+13
Add an alternative to `tcx.all_traits()` that only shows traits that the user might be able to use, for diagnostic purposes. With this available, make use of it for diagnostics including associated type errors, which is part of the problem with [1]. Includes a few comment updates for related API. [1]: https://github.com/rust-lang/rust/issues/135232
2025-01-14Make `#[rustc_private]` override dependency visibilityTrevor Gross-0/+5
Really this is always-visible override only needs to happen when the crate is a dependency of itself. However, this is a very internal feature, so it doesn't seem worth doing any additional filtering here.
2025-01-14Rollup merge of #135451 - mzacho:code-duplication, r=oli-obkMatthias Krüger-1/+0
Remove code duplication when hashing query result and interning node Refactored the duplicated code into a function. `with_feed_task` currently passes the query key to `debug_assert!`. I believe that's a mistake, since `with_task` prints the `DepNode` which is more sensible, so this commit changes that, so it debug prints the `DepNode`.
2025-01-14Auto merge of #135465 - jhpratt:rollup-7p93bct, r=jhprattbors-9/+15
Rollup of 10 pull requests Successful merges: - #134498 (Fix cycle error only occurring with -Zdump-mir) - #134977 (Detect `mut arg: &Ty` meant to be `arg: &mut Ty` and provide structured suggestion) - #135390 (Re-added regression test for #122638) - #135393 (uefi: helpers: Introduce OwnedDevicePath) - #135440 (rm unnecessary `OpaqueTypeDecl` wrapper) - #135441 (Make sure to mark `IMPL_TRAIT_REDUNDANT_CAPTURES` as `Allow` in edition 2024) - #135444 (Update books) - #135450 (Fix emscripten-wasm-eh with unwind=abort) - #135452 (bootstrap: fix outdated feature name in comment) - #135454 (llvm: Allow sized-word rather than ymmword in tests) r? `@ghost` `@rustbot` modify labels: rollup
2025-01-13Rollup merge of #134498 - oli-obk:push-wmxynprsyxvr, r=compiler-errorsJacob Pratt-9/+15
Fix cycle error only occurring with -Zdump-mir fixes #134205 During mir dumping, we evaluate static items to render their allocations. If a static item refers to itself, its own MIR will have a reference to itself, so during mir dumping we end up evaluating the static again, causing us to try to build MIR again (mir dumping happens during MIR building). Thus I disabled evaluation of statics during MIR dumps in case the MIR body isn't far enough along yet to be able to be guaranteed cycle free.
2025-01-13remove code duplication when hashing query result and interning nodeMartin Zacho-1/+0
Refactored the duplicated code into a function. `with_feed_task` currently passes the query key to `debug_assert!`. This commit changes that, so it debug prints the `DepNode`, as in `with_task`.
2025-01-13Rollup merge of #135426 - compiler-errors:no-resolve-assoc-ty, r=lcnrMatthias Krüger-153/+20
Assert that `Instance::try_resolve` is only used on body-like things `Instance::resolve` is not set up to resolve items that are not body-like things. The logic in `resolve_associated_item` very much encodes this assumption: https://github.com/rust-lang/rust/blob/e7ad3ae331bf2716389c10e01612e201a7f98c8d/compiler/rustc_ty_utils/src/instance.rs#L96-L386 However, some diagnostics were using `Instance::resolve` on an associated type, and it was simply a lucky coicidence that nothing went wrong. This PR adds an assertion to make sure we won't do this again in the future, and fixes two callsites: 1. `call_kind` which returns a `CallKind` enum to categorize what a call in MIR comes from, and was using `Instance::resolve` to point at the associated type `Deref::Target` for a specific self ty. 2. `MirBorrowckCtxt::explain_deref_coercion`, which was doing the same thing. The logic was replaced with `specialization_graph::assoc_def`, which is the proper way of fetching the right `AssocItem` for a given impl. r? `@lcnr` or re-roll :)
2025-01-13Auto merge of #135167 - mzacho:depth-limit-const-eval-query, r=oli-obkbors-0/+1
Depth limit const eval query Currently the const-eval query doesn't have a recursion limit or timeout, causing the complier to freeze in an infinite loop, see #125718. This PR depth limits the `eval_to_const_value_raw` query (with the [`recursion_limit`](https://doc.rust-lang.org/reference/attributes/limits.html) attribute) and improves the diagnostics for query overflow errors, so spans are reported for other dep kinds than `layout_of` (e.g. `eval_to_const_value_raw`). fixes #125718 fixes #114192
2025-01-13Assert that Instance::try_resolve is only used on body-like thingsMichael Goulet-153/+20
2025-01-12Rollup merge of #135383 - BoxyUwU:cov_tag_ptr, r=compiler-errorsGuillaume Gomez-1/+1
De-abstract tagged ptr and make it covariant In #135272 I needed to use a tagged ptr in `hir::TyKind` in order to not regress hir type sizes. Unfortunately the existing `CopyTaggedPtr` abstraction is insufficient as it makes the `'hir` lifetime invariant. I spent some time trying to keep existing functionality while making it covariant but in the end I realised that actually we dont use *any* of this code *anywhere* in rustc, so I've just removed everything and replaced it with a much less general abstraction that is suitable for what I need in #135272. Idk if anyone has a preference for just keeping all the abstractions here in case anyone needs them in the future :woman_shrugging:
2025-01-12De-abstract tagged pointer abstractionBoxy-1/+1
2025-01-12Rollup merge of #135378 - compiler-errors:unnecessary-stashing, r=chenyukangMatthias Krüger-11/+1
Remove a bunch of diagnostic stashing that doesn't do anything #121669 removed a bunch of conditional diagnostic stashing/canceling, but left around the `steal` calls which just emitted the error eagerly instead of canceling the diagnostic. I think that these no-op `steal` calls don't do much and are confusing to encounter, so let's remove them. The net effect is: 1. We emit more duplicated errors, since stashing has the side effect of duplicating diagnostics. This is not a big deal, since outside of `-Zdeduplicate-diagnostics=no`, the errors are already being deduplicated by the compiler. 2. It changes the order of diagnostics, since we're no longer stashing and then later stealing the errors. I don't think this matters much for the changes that the UI test suite manifests, and it makes these errors less order dependent.
2025-01-11Remove a bunch of diagnostic stashing that doesn't do anythingMichael Goulet-11/+1
2025-01-11Rollup merge of #135314 - compiler-errors:eagerly-mono-closures, r=wesleywiserMatthias Krüger-0/+13
Eagerly collect mono items for non-generic closures This allows users to use `-Zprint-mono-items=eager` to eagerly monomorphize closures and coroutine bodies, in case they want to inspect the LLVM or ASM for those items. `-Zprint-mono-items`, which used to be called `-Zprint-trans-items`, was originally added in https://github.com/rust-lang/rust/pull/30900: > Eager mode is meant to be used in conjunction with incremental compilation > where a stable set of translation items is more important than a minimal > one. Thus, eager mode will instantiate drop-glue for every drop-able type > in the crate, even of no drop call for that type exists (yet). It will > also instantiate default implementations of trait methods, something that > otherwise is only done on demand. Although it remains an unstable option, its purpose has somewhat expanded since then, and as far as I can tell it's generally useful for cases when you want to monomorphize as many items as possible, even if they're unreachable. Specifically, it's useful for debugging since you can look at the codegen'd body of a function, since we don't emit items that are not reachable in monomorphization. And even more specifically, it would be very to monomorphize the coroutine body of an async fn, since those you can't easily call those without a runtime. This PR enables this usecase since we now monomorphize `DefKind::Closure`.
2025-01-11rename `BitSet` to `DenseBitSet`Rémy Rakic-21/+21
This should make it clearer that this bitset is dense, with the advantages and disadvantages that it entails.
2025-01-10mir_transform: implement forced inliningDavid Wood-3/+7
Adds `#[rustc_force_inline]` which is similar to always inlining but reports an error if the inlining was not possible, and which always attempts to inline annotated items, regardless of optimisation levels. It can only be applied to free functions to guarantee that the MIR inliner will be able to resolve calls.
2025-01-10Fix cycle error only occurring with -Zdump-mirOli Scherer-9/+15
2025-01-10Rollup merge of #133088 - the8472:randomize-me-harder, r=workingjubileeMatthias Krüger-0/+1
`-Zrandomize-layout` harder. `Foo<T> != Foo<U>` Tracking issue: #106764 Previously randomize-layout only used a deterministic shuffle based on the seed stored in an Adt's ReprOptions, meaning that `Foo<T>` and `Foo<U>` were shuffled by the same seed. This change adds a similar seed to each calculated LayoutData so that a struct can be randomized both based on the layout of its fields and its per-type seed. Primitives start with simple seed derived from some of their properties. Though some types can no longer be distinguished at that point, e.g. usize and u64 will still be treated the same.
2025-01-10Eagerly collect mono items for non-generic closuresMichael Goulet-0/+13
2025-01-10Foo<T> != Foo<U> under layout randomizationThe 8472-0/+1
previously field ordering was using the same seed for all instances of Foo, now we pass seed values through the layout tree so that not only the struct itself affects layout but also its fields
2025-01-09Rollup merge of #135261 - compiler-errors:coverage-has-identity-substs, ↵Matthias Krüger-4/+8
r=oli-obk Account for identity substituted items in symbol mangling See the inline comment. r? oli-obk Fixes #135235
2025-01-09Account for identity substituted items in symbol manglingMichael Goulet-4/+8
2025-01-09Harden `Ty` constructors a bit in debug modeOli Scherer-2/+37
`Ty::new` wasn't used anywhere outside this module `Ty::new_adt` shouldn't ever be used for anything but adts. This hasn't caught any bugs, but seems good to check anyway
2025-01-09Remove the now-useless `Result` from `lit_to_const`Oli Scherer-20/+2
2025-01-09Use error constant instead of explicit error handlingOli Scherer-2/+0
2025-01-09Rollup merge of #134875 - compiler-errors:const-destruct-old-solver, r=lcnrMatthias Krüger-2/+2
Implement `const Destruct` in old solver Self-explanatory. Not totally settled that this is the best structure for built-in trait impls for effect goals in the new solver, but it's almost certainly the simplest. r? lcnr or re-roll
2025-01-09Rollup merge of #128110 - veera-sivarajan:bugfix-80173, r=cjgillotMatthias Krüger-1/+13
Suggest Replacing Comma with Semicolon in Incorrect Repeat Expressions Fixes #80173 This PR detects typos in repeat expressions like `["_", 10]` and `vec![String::new(), 10]` and suggests replacing comma with semicolon. Also, improves code in other place by adding doc comments and making use of a helper function to check if a type implements `Clone`. References: 1. For `vec![T; N]`: https://doc.rust-lang.org/std/macro.vec.html 2. For `[T; N]`: https://doc.rust-lang.org/std/primitive.array.html
2025-01-08Implement const Destruct in old solverMichael Goulet-2/+2
2025-01-08Rollup merge of #134228 - oli-obk:pat-lit-path, r=compiler-errorsMatthias Krüger-0/+2
Exhaustively handle expressions in patterns We currently have this invariant in HIR that a `PatKind::Lit` or a `PatKind::Range` only contains * `ExprKind::Lit` * `ExprKind::UnOp(Neg, ExprKind::Lit)` * `ExprKind::Path` * `ExprKind::ConstBlock` So I made `PatKind::Lit` and `PatKind::Range` stop containing `Expr`, and instead created a `PatLit` type whose `kind` enum only contains those variants. The only place code got more complicated was in clippy, as it couldn't share as much anymore with `Expr` handling It may be interesting on merging `ExprKind::{Path,Lit,ConstBlock}` in the future and using the same `PatLit` type (under a new name). Then it should also be easier to eliminate any and all `UnOp(Neg, Lit) | Lit` matching that we have across the compiler. Some day we should fold the negation into the literal itself and just store it on the numeric literals
2025-01-08Auto merge of #133858 - dianne:better-blame-constraints-for-static, r=lcnrbors-11/+12
`best_blame_constraint`: Blame better constraints when the region graph has cycles from invariance or `'static` This fixes #132749 by changing which constraint is blamed for region errors in several cases. `best_blame_constraint` had a heuristic that tried to pinpoint the constraint causing an error by filtering out any constraints where the outliving region is unified with the ultimate target region being outlived. However, it used the SCCs of the region graph to do this, which is unreliable; in particular, if the target region is `'static`, or if there are cycles from the presence of invariant types, it was skipping over the constraints it should be blaming. As is the case in that issue, this could lead to confusing diagnostics. The simplest fix seems to work decently, judging by test stderr: this makes `best_blame_constraint` no longer filter constraints by their outliving region's SCC. There are admittedly some quirks in the test output. In many cases, subdiagnostics that depend on the particular constraint being blamed have either started or stopped being emitted. After starting at this for quite a while, I think anything too fickle about whether it outputs based on the particular constraint being blamed should instead be looking at the constraint path as a whole, similar to what's done for [the placeholder-from-predicate note](https://github.com/rust-lang/rust/compare/master...dianne:rust:better-blame-constraints-for-static#diff-3c0de6462469af483c9ecdf2c4b00cb26192218ef2d5c62a0fde75107a74caaeR506). Very many tests involving invariant types gained a note pointing out the types' invariance, but in a few cases it was lost. A particularly illustrative example is [tests/ui/lifetimes/copy_modulo_regions.stderr](https://github.com/rust-lang/rust/compare/master...dianne:rust:better-blame-constraints-for-static?expand=1#diff-96e1f8b29789b3c4ce2f77a5e0fba248829b97ef9d1ce39e7d2b4aa57b2cf4f0); I'd argue the new constraint is a better one to blame, but it lacks the variance diagnostic information that's elsewhere in the constraint path. If desired, I can try making that note check the whole path rather than just the blamed constraint. The subdiagnostic [`BorrowExplanation::add_object_lifetime_default_note`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/diagnostics/explain_borrow/enum.BorrowExplanation.html#method.add_object_lifetime_default_note) depends on a `Cast` being blamed, so [a special case](https://github.com/rust-lang/rust/pull/133858/commits/364ca7f99c12fb5220e6b568ac391979317ce878) was necessary to keep it from disappearing from tests specifically testing for it. However, see the FIXME comment in that commit; I think the special case should be removed once that subdiagnostic works properly, but it's nontrivial enough to warrant a separate PR. Incidentally, this removes the note from a test where it was being added erroneously: in [tests/ui/borrowck/two-phase-surprise-no-conflict.stderr](https://github.com/rust-lang/rust/compare/master...dianne:rust:better-blame-constraints-for-static?expand=1#diff-8cf085af8203677de6575a45458c9e6b03412a927df879412adec7e4f7ff5e14), the object lifetime is explicitly provided and it's not `'static`.
2025-01-08Exhaustively handle expressions in patternsOli Scherer-0/+2
2025-01-08Rollup merge of #134920 - lqd:polonius-next-episode-6, r=jackh726Jacob Pratt-0/+2
Convert typeck constraints in location-sensitive polonius In this PR, we do a big chunk of the work of localizing regular outlives constraints. The slightly annoying thing is handling effectful statements: usually the subset graph propagates loans at a single point between regions, and liveness propagates loans between points within a single region, but some statements have effects applied on exit. This was also a problem before, in datalog polonius terms and Niko's solution at the time, this is about: the mid-point. The idea was to duplicate all MIR locations into two physical points, and orchestrate the effects with that. Somewhat easier to do, but double the CFG. We've always believed we didn't _need_ midpoints in principle, as we can represent changes on exit as on happening entry to the successor, but there's some difficulty in tracking the position information at sufficient granularity through outlives relation (especially since we also have bidirectional edges and time-traveling now). Now, that is surely what we should be doing in the future. In the mean time, I infer this from the kind of statement/terminator where an outlives constraint arose. It's not particularly complicated but some explanation will help clarify the code. Assignments (in their various forms) are the quintessential example of these crossover cases: loans that would flow into the LHS would not be visible on entry to the point but on exit -- so we'll localize these edges to the successor. Let's look at a real-world example, involving invariance for bidirectional edges: ```rust let mut _1: HashMap<i32, &'7 i32>; let mut _3: &'9 mut HashMap<i32, &'10 i32>; ... /* at bb1[3]: */ _3 = &'3 mut _1; ``` Here, typeck expectedly produces 3 outlives constraints today: 1. `'3 -> '9` 2. `'7 -> '10` 3. `'10 -> '7` And we localize them like so, 1. `'3 -> '9` flows into the LHS and becomes: `3_bb1_3 -> 9_bb1_4` 2. `'7 -> '10` flows into the LHS and becomes: `7_bb1_3 -> 10_bb1_4` 3. `'10 -> '7` flows from the LHS and becomes: `10_bb1_4 -> 7_bb1_3` (time traveling 👌) --- r? ``@jackh726`` To keep you entertained during the holidays I also threw in a couple of small changes removing cruft in the borrow checker. We're actually getting there. The next PR will be the last one needed to get end-to-end tests working.
2025-01-07Rollup merge of #135149 - compiler-errors:mangle, r=oli-obkMatthias Krüger-21/+19
Use a post-monomorphization typing env when mangling components that come from impls When mangling associated methods of impls, we were previously using the wrong param-env. Instead of using a fully monomorphized param-env like we usually do in codegen, we were taking the post-analysis param-env, and treating it as an early binder to *re-substitute* the impl args. I've pointed out the problematic old code in an inline comment. This would give us param-envs with possibly trivial predicates that would prevent normalization via param-env shadowing. In the example test linked below, `tests/ui/symbol-names/normalize-in-param-env.rs`, this happens when we mangle the impl `impl<P: Point2> MyFrom<P::S> for P` with the substitution `P = Vec2`. Because the where clause of the impl is `P: Point2`, which elaborates to `[P: Point2, P: Point, <P as Point>::S projects-to <P as Point2>::S2]` and the fact that `impl Point2 for Vec2` normalizes `Vec2::S2` to `Vec2::S`, this causes a cycle. The proper fix here is to use a fully monomorphized param-env for the case where the impl is properly substituted. Fixes #135143 While #134081 uncovered this bug for legacy symbol mangling, it was preexisting for v0 symbol mangling. This PR fixes both. The test requires a "hack" because we strip the args of the instance we're printing for legacy symbol mangling except for drop glue, so we box a closure to ensure we generate drop glue. r? oli-obk
2025-01-06only avoid blaming assignments from argument patternsdianne-6/+1
2025-01-06make outlives constraints from generic arguments less boringdianne-1/+10
2025-01-06`best_blame_constraint`: prioritize blaming interesting-seeming constraintsdianne-5/+2
2025-01-06remove the unused `ConstraintCategory::ClosureBounds`dianne-5/+0
2025-01-06`best_blame_constraint`: avoid blaming assignments without user-provided typesdianne-1/+6
2025-01-06Add derived causes for host effect predicatesMichael Goulet-17/+94
2025-01-06depth limit eval_to_const_value_rawMartin Zacho-0/+1
2025-01-06Rollup merge of #135147 - compiler-errors:borrowck-tweaks, r=chenyukangMatthias Krüger-19/+22
A few borrowck tweaks to improve 2024 edition migration lints See first two commits' changes to test outputs. Test coverage in this area is kinda weak, but I think it affects more cases than this (like the craters that will begin to trigger the `tail_expr_drop_order` tests in #134523). Third commit is a drive-by change that removes a deref hack from `UseSpans` which doesn't really improve diagnostics much.
2025-01-06Use a post-monomorphization typing env when mangling components that come ↵Michael Goulet-21/+19
from impls
2025-01-06Improve find_self_call with reborrowed receiverMichael Goulet-19/+22