about summary refs log tree commit diff
path: root/compiler/rustc_trait_selection/src
AgeCommit message (Collapse)AuthorLines
2025-06-26Rollup merge of #140942 - RalfJung:const-ref-to-mut, r=oli-obkMichael Goulet-2/+4
const-eval: allow constants to refer to mutable/external memory, but reject such constants as patterns This fixes https://github.com/rust-lang/rust/issues/140653 by accepting code such as this: ```rust static FOO: AtomicU32 = AtomicU32::new(0); const C: &'static AtomicU32 = &FOO; ``` This can be written entirely in safe code, so there can't really be anything wrong with it. We also accept the much more questionable following code, since it looks very similar to the interpreter: ```rust static mut FOO2: u32 = 0; const C2: &'static u32 = unsafe { &mut FOO2 }; ``` Using this without causing UB is at least very hard (the details are unclear since it is related to how the aliasing model deals with the staging of const-eval vs runtime code). If a constant like `C2` is used as a pattern, we emit an error: ``` error: constant BAD_PATTERN cannot be used as pattern --> $DIR/const_refs_to_static_fail.rs:30:9 | LL | BAD_PATTERN => {}, | ^^^^^^^^^^^ | = note: constants that reference mutable or external memory cannot be used as pattern ``` (If you somehow manage to build a pattern with constant `C`, you'd get the same error, but that should be impossible: we don't have a type that can be used in patterns and that has interior mutability.) The same treatment is afforded for shared references to `extern static`, for the same reason: the const evaluation is entirely fine with it, we just can't build a pattern for it -- and when using interior mutability, this can be totally sound. We do still not accept anything where there is an `&mut` in the final value of the const, as that should always require unsafe code and it's hard to imagine a sound use-case that would require this.
2025-06-26Auto merge of #143057 - matthiaskrgr:rollup-bulih8o, r=matthiaskrgrbors-35/+92
Rollup of 8 pull requests Successful merges: - rust-lang/rust#124595 (Suggest cloning `Arc` moved into closure) - rust-lang/rust#139594 (Simplify `ObligationCauseCode::IfExpression`) - rust-lang/rust#141311 (make `tidy-alphabetical` use a natural sort) - rust-lang/rust#141648 ([rustdoc] Do not emit redundant_explicit_links lint if the doc comment comes from expansion) - rust-lang/rust#142285 (tests: Do not run afoul of asm.validity.non-exhaustive in input-stats) - rust-lang/rust#142393 (Don't give APITs names with macro expansion placeholder fragments in it) - rust-lang/rust#142884 (StableMIR: Add method to retrieve body of coroutine) - rust-lang/rust#142981 (Make missing lifetime suggestion verbose) r? `@ghost` `@rustbot` modify labels: rollup
2025-06-26Auto merge of #142774 - lcnr:search_graph-2, r=oli-obkbors-6/+6
`evaluate_goal` avoid unnecessary step based on rust-lang/rust#142617. This does not mess with the debug logging for the trait solver and is a very nice cleanup for rust-lang/rust#142735. E.g. for ```rust #[derive(Clone)] struct Wrapper<T>(T); #[derive(Clone)] struct Nested; // using a separate type to avoid the fast paths fn is_clone<T: Clone>() {} fn main() { is_clone::<Wrapper<Nested>>(); } ``` We get the following proof tree with `RUSTC_LOG=rustc_type_ir::search_graph=debug,rustc_next_trait_solver=debug` ``` rustc_next_trait_solver::solve::eval_ctxt::evaluate_root_goal goal=Goal { param_env: ParamEnv { caller_bounds: [] }, predicate: Binder { value: TraitPredicate(<Wrapper<Nested> as std::clone::Clone>, polarity:Positive), bound_vars: [] } }, generate_proof_tree=No, span=src/main.rs:7:5: 7:34 (#0), stalled_on=None rustc_type_ir::search_graph::evaluate_goal input=CanonicalQueryInput { canonical: Canonical { value: QueryInput { goal: Goal { param_env: ParamEnv { caller_bounds: [] }, predicate: Binder { value: TraitPredicate(<Wrapper<Nested> as std::clone::Clone>, polarity:Positive), bound_vars: [] } }, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [] }, typing_mode: Analysis { defining_opaque_types_and_generators: [] } }, step_kind_from_parent=Unknown rustc_next_trait_solver::solve::eval_ctxt::probe::enter source=Impl(DefId(0:10 ~ main[21d2]::{impl#0})) rustc_next_trait_solver::solve::eval_ctxt::add_goal source=ImplWhereBound, goal=Goal { param_env: ParamEnv { caller_bounds: [] }, predicate: Binder { value: TraitPredicate(<_ as std::marker::Sized>, polarity:Positive), bound_vars: [] } } rustc_next_trait_solver::solve::eval_ctxt::add_goal source=ImplWhereBound, goal=Goal { param_env: ParamEnv { caller_bounds: [] }, predicate: Binder { value: TraitPredicate(<_ as std::clone::Clone>, polarity:Positive), bound_vars: [] } } rustc_type_ir::search_graph::evaluate_goal input=CanonicalQueryInput { canonical: Canonical { value: QueryInput { goal: Goal { param_env: ParamEnv { caller_bounds: [] }, predicate: Binder { value: TraitPredicate(<Nested as std::clone::Clone>, polarity:Positive), bound_vars: [] } }, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [] }, typing_mode: Analysis { defining_opaque_types_and_generators: [] } }, step_kind_from_parent=Unknown 0ms DEBUG rustc_type_ir::search_graph global cache hit, required_depth=0 0ms DEBUG rustc_type_ir::search_graph return=Ok(Canonical { value: Response { certainty: Yes, var_values: CanonicalVarValues { var_values: [] }, external_constraints: ExternalConstraints(ExternalConstraintsData { region_constraints: [], opaque_types: [], normalization_nested_goals: NestedNormalizationGoals([]) }) }, max_universe: U0, variables: [] }) rustc_next_trait_solver::solve::eval_ctxt::probe::enter source=BuiltinImpl(Misc) rustc_next_trait_solver::solve::trait_goals::merge_trait_candidates candidates=[Candidate { source: Impl(DefId(0:10 ~ main[21d2]::{impl#0})), result: Canonical { value: Response { certainty: Yes, var_values: CanonicalVarValues { var_values: [] }, external_constraints: ExternalConstraints(ExternalConstraintsData { region_constraints: [], opaque_types: [], normalization_nested_goals: NestedNormalizationGoals([]) }) }, max_universe: U0, variables: [] } }] 0ms DEBUG rustc_next_trait_solver::solve::trait_goals return=Ok((Canonical { value: Response { certainty: Yes, var_values: CanonicalVarValues { var_values: [] }, external_constraints: ExternalConstraints(ExternalConstraintsData { region_constraints: [], opaque_types: [], normalization_nested_goals: NestedNormalizationGoals([]) }) }, max_universe: U0, variables: [] }, Some(Misc))) 0ms DEBUG rustc_type_ir::search_graph insert global cache, evaluation_result=EvaluationResult { encountered_overflow: false, required_depth: 1, heads: CycleHeads { heads: {} }, nested_goals: NestedGoals { nested_goals: {} }, result: Ok(Canonical { value: Response { certainty: Yes, var_values: CanonicalVarValues { var_values: [] }, external_constraints: ExternalConstraints(ExternalConstraintsData { region_constraints: [], opaque_types: [], normalization_nested_goals: NestedNormalizationGoals([]) }) }, max_universe: U0, variables: [] }) } 0ms DEBUG rustc_type_ir::search_graph return=Ok(Canonical { value: Response { certainty: Yes, var_values: CanonicalVarValues { var_values: [] }, external_constraints: ExternalConstraints(ExternalConstraintsData { region_constraints: [], opaque_types: [], normalization_nested_goals: NestedNormalizationGoals([]) }) }, max_universe: U0, variables: [] }) ```
2025-06-26const-eval: allow constants to refer to mutable/external memory, but reject ↵Ralf Jung-2/+4
such constants as patterns
2025-06-26Change const trait bound syntax from ~const to [const]Oli Scherer-12/+12
2025-06-26Simplify IfCauseMichael Goulet-35/+92
2025-06-25Rollup merge of #142724 - xizheyin:avoid_overwrite_args, r=oli-obkJana Dönszelmann-0/+2
Add runtime check to avoid overwrite arg in `Diag` ## Origin PR description At first, I set up a `debug_assert` check for the arg method to make sure that `args` in `Diag` aren't easily overwritten, and I added the `remove_arg()` method, so that if you do need to overwrite an arg, then you can explicitly call `remove_arg()` to remove it first, then call `arg()` to overwrite it. For the code before the rust-lang/rust#142015 change, it won't compile because it will report an error ``` arg `instance`already exists. ``` This PR also modifies all diagnostics that fail the check to pass the check. There are two cases of check failure: 1. ~~Between *the parent diagnostic and the subdiagnostic*, or *between the subdiagnostics* have the same field between them. In this case, I renamed the conflicting fields.~~ 2. ~~For subdiagnostics stored in `Vec`, the rendering may iteratively write the same arg over and over again. In this case, I changed the auto-generation with `derive(SubDiagnostic)` to manually implementing `SubDiagnostic` and manually rendered it with `eagerly_translate()`, similar to https://github.com/rust-lang/rust/issues/142031#issuecomment-2984812090, and after rendering it I manually deleted useless arg with the newly added `remove_arg` method.~~ ## Final Decision After trying and discussing, we made a final decision. For `#[derive(Subdiagnostic)]`, This PR made two changes: 1. After the subdiagnostic is rendered, remove all args of this subdiagnostic, which allows for usage like `Vec<Subdiag>`. 2. Store `diag.args` before setting arguments, so that you can restore the contents of the main diagnostic after deleting the arguments after subdiagnostic is rendered, to avoid deleting the main diagnostic's arg when they have the same name args.
2025-06-25rename RegionVariableOrigin::MiscVariable to RegionVariableOrigin::MiscMichael Goulet-2/+2
2025-06-25Remove some glob imports from the type systemMichael Goulet-95/+119
2025-06-25Compute hard errors without diagnostics in ↵Michael Goulet-17/+26
impl_intersection_has_impossible_obligation
2025-06-25Add runtime check to avoid overwrite arg easily in diag and store and ↵xizheyin-0/+2
restore snapshot when set subdiag arg Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-06-24Apply fast path to old solver tooMichael Goulet-2/+10
2025-06-24Introduce trivial WF functions, use it in fast pathMichael Goulet-0/+10
2025-06-23Simplify API of solver a bitMichael Goulet-43/+19
2025-06-23Add note to find_const_ty_from_envMichael Goulet-3/+5
2025-06-23inspect: merge `[Canonical]GoalEvaluation`lcnr-6/+6
2025-06-22Rollup merge of #142594 - mejrs:new_desugaring, r=chenyukangGuillaume Gomez-7/+25
Add DesugaringKind::FormatLiteral Implements `DesugaringKind::FormatLiteral` to mark the FormatArgs desugaring of format literals. The main use for this is to stop yapping about about formatting parameters if we're not anywhere near a format literal. The other use case is to fix suggestions such as https://github.com/rust-lang/rust/issues/141350. It might also be useful for new or existing diagnostics that check whether they're in a format-like macro. cc `@xizheyin` `@fmease`
2025-06-22Rollup merge of #142458 - oli-obk:dyn-incompat, r=compiler-errorsGuillaume Gomez-1/+8
Merge unboxed trait object error suggestion into regular dyn incompat error Another hir-walker removed from the well-formed queries. This error was always a duplicate of another, but it was able to provide more information because it could invoke `is_dyn_compatible` without worrying about cycle errors. That's also the reason we can't put the error directly into hir_ty_lowering when lowering a `dyn Trait` within an associated item signature. So instead I packed it into the error handling of wf obligation checking.
2025-06-22Implement DesugaringKind::FormatLiteralmejrs-7/+25
2025-06-20Rollup merge of #142687 - cjgillot:less-hir_crate, r=oli-obkTrevor Gross-5/+1
Reduce uses of `hir_crate`. I tried rebasing my old incremental-HIR branch. This is a by-product, which is required if we want to get rid of `hir_crate` entirely. The second commit is a drive-by cleanup. It can be pulled into its own PR. r? ````@oli-obk````
2025-06-18Make feature suggestion more consistent.Camille GILLOT-5/+1
2025-06-18Rollup merge of #142619 - klensy:or_fun_call, r=nnethercoteJakub Beránek-2/+2
apply clippy::or_fun_call Applies https://rust-lang.github.io/rust-clippy/master/index.html?groups=nursery#or_fun_call to reduce needless allocs.
2025-06-17apply clippy::or_fun_callklensy-2/+2
2025-06-16trait_sel: skip `nominal_obligations` for `Sized`David Wood-0/+8
`nominal_obligations` calls `predicates_of` on a `Sized` obligation, effectively elaborating the trait and making the well-formedness checking machinery do a bunch of extra work checking a `MetaSized` obligation is well-formed, but given that both `Sized` and `MetaSized` are built-ins, if `Sized` is otherwise well-formed, so `MetaSized` will be.
2025-06-16trait_sel: skip elaboration of sizedness supertraitDavid Wood-6/+69
As a performance optimization, skip elaborating the supertraits of `Sized`, and if a `MetaSized` obligation is being checked, then look for a `Sized` predicate in the parameter environment. This makes the `ParamEnv` smaller which should improve compiler performance as it avoids all the iteration over the larger `ParamEnv`.
2025-06-16trait_sel: extend fast path with sized hierarchyDavid Wood-10/+21
Extend the fast path for `Sized` traits to include constness and `MetaSized`.
2025-06-16trait_sel: print `{Meta,Pointee}Sized` impl headersDavid Wood-16/+46
When printing impl headers in a diagnostic, the compiler has to account for `?Sized` implying `MetaSized` and new `MetaSized` and `PointeeSized` bounds.
2025-06-16trait_sel: sort `{Meta,Pointee}Sized` diagnostics lastDavid Wood-10/+17
Like `Sized` diagnostics, sorting `MetaSized` and `PointeeSized` diagnostics last prevents earlier more useful diagnostics from being skipped because there has already been error tainting.
2025-06-16trait_sel: `MetaSized` bounds in dispatchable checkDavid Wood-8/+15
Given the necessary additions of bounds to these traits and their impls in the standard library, it is necessary to add `MetaSized` bounds to the obligation which is proven as part of checking for dyn dispatchability.
2025-06-16trait_sel: stash `{Meta,Pointee}Sized` errorsDavid Wood-1/+4
`Sized` errors are currently stashed to improve diagnostics and this must happen with `{Meta,Pointee}Sized` too to maintain diagnostic output.
2025-06-16trait_sel: `{Meta,Pointee}Sized` on `?Sized` typesDavid Wood-19/+39
Expand the automatic implementation of `MetaSized` and `PointeeSized` so that it is also implemented on non-`Sized` types, just not `ty::Foreign` (extern type).
2025-06-16trait_sel: `{Meta,Pointee}Sized` on `Sized` typesDavid Wood-0/+8
Introduce the `MetaSized` and `PointeeSized` traits as supertraits of `Sized` and initially implement it on everything that currently implements `Sized` to isolate any changes that simply adding the traits introduces.
2025-06-14Rollup merge of #141811 - mejrs:bye_locals, r=compiler-errorsMatthias Krüger-5/+2
Unimplement unsized_locals Implements https://github.com/rust-lang/compiler-team/issues/630 Tracking issue here: https://github.com/rust-lang/rust/issues/111942 Note that this just removes the feature, not the implementation, and does not touch `unsized_fn_params`. This is because it is required to support `Box<dyn FnOnce()>: FnOnce()`. There may be more that should be removed (possibly in follow up prs) - the `forget_unsized` function and `forget` intrinsic. - the `unsized_locals` test directory; I've just fixed up the tests for now - various codegen support for unsized values and allocas cc ``@JakobDegen`` ``@oli-obk`` ``@Noratrieb`` ``@programmerjake`` ``@bjorn3`` ``@rustbot`` label F-unsized_locals Fixes rust-lang/rust#79409
2025-06-13Rollup merge of #142441 - compiler-errors:lazier-binder-value-folding, r=lcnrJubilee-151/+6
Delay replacing escaping bound vars in `FindParamInClause` By uplifting the `BoundVarReplacer`, which is used by (e.g.) normalization to replace escaping bound vars that are encountered when folding binders, we can use a similar strategy to delay the instantiation of a binder's contents in the `FindParamInClause` used by the new trait solver. This should alleviate the recently added requirement that `Binder<T>: TypeVisitable` only if `T: TypeFoldable`, which was previously required b/c we were calling `enter_forall` so that we could structurally normalize aliases that we found within the predicates of a param-env clause. r? lcnr
2025-06-13Rollup merge of #141352 - lcnr:no-builtin-preference, r=compiler-errorsJubilee-1/+12
builtin dyn impl no guide inference cc https://github.com/rust-lang/rust/pull/141347 we can already slightly restrict this behavior in the old solver, so why not do so. Needs crater and an FCP. r? `@compiler-errors`
2025-06-13TypeVisiting binders no longer requires TypeFolding its interiorMichael Goulet-2/+2
2025-06-13Uplift BoundVarReplacerMichael Goulet-146/+1
2025-06-13Don't use BTreeMap for mapped_constsMichael Goulet-6/+6
2025-06-13Merge unboxed trait object error suggestion into regular dyn incompat errorOli Scherer-1/+8
2025-06-13Unimplement unsized_localsmejrs-5/+2
2025-06-12Rollup merge of #141474 - mejrs:diagnostic_mode, r=compiler-errorsMatthias Krüger-75/+55
Add `ParseMode::Diagnostic` and fix multiline spans in diagnostic attribute lints Best viewed commit by commit. The first commit is a test, the commits following that are small refactors to `rustc_parse_format`. Originally I wanted to do a much larger change (doing these smaller fixes first would have that made easier to review), but ended up doing something else instead. An observable change from this is that the diagnostic attribute no longer tries to parse align/fill/width/etc parameters. For an example (see also test changes), a string like `"{Self:!}"` no longer says "missing '}'", instead it says that format parameters are not allowed. It'll now also format the string as if the user wrote just `"{Self}"`
2025-06-12Auto merge of #142127 - compiler-errors:nested-goals-certainty, r=lcnrbors-35/+64
Apply nested goals certainty to `InspectGoals` for normalizes-to ...so that normalizes-to goals don't have `Certainty::Yes` even if they have nested goals which don't hold. r? lcnr
2025-06-12Rollup merge of #142040 - jswrenn:transmute-ty-region-generic, r=compiler-errorsMatthias Krüger-105/+53
transmutability: shift abstraction boundary Previously, `rustc_transmute`'s layout representations were genericized over `R`, a reference. Now, it's instead genericized over representations of type and region. This allows us to move reference transmutability logic from `rustc_trait_selection` to `rustc_transmutability` (and thus unit test it independently of the compiler), and — in a follow-up PR — will make it possible to support analyzing function pointer transmutability with minimal surgery. r? `@compiler-errors`
2025-06-11Auto merge of #142358 - matthiaskrgr:rollup-fxe6m7k, r=matthiaskrgrbors-4/+8
Rollup of 9 pull requests Successful merges: - rust-lang/rust#141967 (Configure bootstrap backport nominations through triagebot) - rust-lang/rust#142042 (Make E0621 missing lifetime suggestion verbose) - rust-lang/rust#142272 (tests: Change ABIs in tests to more future-resilient ones) - rust-lang/rust#142282 (Only run `citool` tests on the `auto` branch) - rust-lang/rust#142297 (Implement `//@ needs-target-std` compiletest directive) - rust-lang/rust#142298 (Make loongarch-none target maintainers more easily pingable) - rust-lang/rust#142306 (Dont unwrap and re-wrap typing envs) - rust-lang/rust#142324 (Remove unneeded `FunctionCx` from some codegen methods) - rust-lang/rust#142328 (feat: Add `bit_width` for unsigned integer types) Failed merges: - rust-lang/rust#141639 (Expose discriminant values in stable_mir) r? `@ghost` `@rustbot` modify labels: rollup
2025-06-11Auto merge of #141763 - lcnr:fixme-gamer, r=BoxyUwUbors-1/+1
`FIXME(-Znext-solver)` triage r? `@BoxyUwU`
2025-06-09Make E0621 missing lifetime suggestion verboseEsteban Küber-4/+8
``` error[E0621]: explicit lifetime required in the type of `x` --> $DIR/42701_one_named_and_one_anonymous.rs:10:9 | LL | &*x | ^^^ lifetime `'a` required | help: add explicit lifetime `'a` to the type of `x` | LL | fn foo2<'a>(a: &'a Foo, x: &'a i32) -> &'a i32 { | ++ ```
2025-06-09Apply nested goals certainty to InspectGoals for normalizes-toMichael Goulet-35/+64
2025-06-09Introduce ParseMode::diagnostic and fix multiline spansmejrs-40/+32
2025-06-09change FormatString::parse to only return the first errormejrs-40/+28
2025-06-09transmutability: shift abstraction boundaryJack Wrenn-105/+53
Previously, `rustc_transmute`'s layout representations were genericized over `R`, a reference. Now, it's instead genericized over representations of type and region. This allows us to move reference transmutability logic from `rustc_trait_selection` to `rustc_transmutability` (and thus unit test it independently of the compiler), and — in a follow-up PR — will make it possible to support analyzing function pointer transmutability with minimal surgery.