about summary refs log tree commit diff
path: root/compiler/rustc_trait_selection/src
AgeCommit message (Collapse)AuthorLines
2025-04-16Move eager translation to a method on `Diag`Jake Goulding-68/+20
This will allow us to eagerly translate messages on a top-level diagnostic, such as a `LintDiagnostic`. As a bonus, we can remove the awkward closure passed into Subdiagnostic and make better use of `Into`.
2025-04-16Fix replacing supertrait aliases in ReplaceProjectionWithMichael Goulet-4/+6
2025-04-16Rename `LifetimeName` as `LifetimeKind`.Nicholas Nethercote-7/+7
It's a much better name, more consistent with how we name such things. Also rename `Lifetime::res` as `Lifetime::kind` to match. I suspect this field used to have the type `LifetimeRes` and then the type was changed but the field name remained the same.
2025-04-15Auto merge of #139845 - Zalathar:rollup-u5u5y1v, r=Zalatharbors-55/+62
Rollup of 17 pull requests Successful merges: - #138374 (Enable contracts for const functions) - #138380 (ci: add runners for vanilla LLVM 20) - #138393 (Allow const patterns of matches to contain pattern types) - #139517 (std: sys: process: uefi: Use NULL stdin by default) - #139554 (std: add Output::exit_ok) - #139660 (compiletest: Add an experimental new executor to replace libtest) - #139669 (Overhaul `AssocItem`) - #139671 (Proc macro span API redesign: Replace proc_macro::SourceFile by Span::{file, local_file}) - #139750 (std/thread: Use default stack size from menuconfig for NuttX) - #139772 (Remove `hir::Map`) - #139785 (Let CStrings be either 1 or 2 byte aligned.) - #139789 (do not unnecessarily leak auto traits in item bounds) - #139791 (drop global where-bounds before merging candidates) - #139798 (normalize: prefer `ParamEnv` over `AliasBound` candidates) - #139822 (Fix: Map EOPNOTSUPP to ErrorKind::Unsupported on Unix) - #139833 (Fix some HIR pretty-printing problems) - #139836 (Basic tests of MPMC receiver cloning) r? `@ghost` `@rustbot` modify labels: rollup
2025-04-15Rollup merge of #139669 - nnethercote:overhaul-AssocItem, r=oli-obkStuart Cook-55/+62
Overhaul `AssocItem` `AssocItem` has multiple fields that only make sense some of the time. E.g. the `name` can be empty if it's an RPITIT associated type. It's clearer and less error prone if these fields are moved to the relevant `kind` variants. r? ``@fee1-dead``
2025-04-15Auto merge of #139826 - matthiaskrgr:rollup-0q0qvkd, r=matthiaskrgrbors-19/+8
Rollup of 8 pull requests Successful merges: - #139745 (Avoid unused clones in `Cloned<I>` and `Copied<I>`) - #139757 (opt-dist: use executable-extension for host llvm-profdata) - #139778 (Add test for issue 34834) - #139783 (Use `compiletest-ignore-dir` for bootstrap self-tests) - #139797 (Allow (but don't require) `#[unsafe(naked)]` so that `compiler-builtins` can upgrade to it) - #139799 (Specify `--print info=file` syntax in `--help`) - #139811 (Use `newtype_index!`-generated types more idiomatically) - #139813 (Miri subtree update) r? `@ghost` `@rustbot` modify labels: rollup
2025-04-15Move `name` field from `AssocItem` to `AssocKind` variants.Nicholas Nethercote-32/+39
To accurately reflect that RPITIT assoc items don't have a name. This avoids the use of `kw::Empty` to mean "no name", which is error prone. Helps with #137978.
2025-04-15Move two methods from `AssocKind` to `AssocItem`.Nicholas Nethercote-1/+1
Because all the other similar methods are on `AssocItem`.
2025-04-15Move `opt_rpitit_info` field to `hir::AssocKind::Type`.Nicholas Nethercote-10/+10
From `hir::AssocItem`.
2025-04-14Auto merge of #139577 - davidtwco:sizedness-go-vroom, r=oli-obkbors-15/+35
re-use `Sized` fast-path There's an existing fast path for the `type_op_prove_predicate` predicate, checking for trivially `Sized` types, which can be re-used when evaluating obligations within queries. This should improve performance and was found to be beneficial in #137944. r? types
2025-04-14Use `newtype_index!`-generated types more idiomaticallyYotam Ofek-19/+8
2025-04-14Move `has_self` field to `hir::AssocKind::Fn`.Nicholas Nethercote-14/+14
`hir::AssocItem` currently has a boolean `fn_has_self_parameter` field, which is misplaced, because it's only relevant for associated fns, not for associated consts or types. This commit moves it (and renames it) to the `AssocKind::Fn` variant, where it belongs. This requires introducing a new C-style enum, `AssocTag`, which is like `AssocKind` but without the fields. This is because `AssocKind` values are passed to various functions like `find_by_ident_and_kind` to indicate what kind of associated item should be searched for, and having to specify `has_self` isn't relevant there. New methods: - Predicates `AssocItem::is_fn` and `AssocItem::is_method`. - `AssocItem::as_tag` which converts `AssocItem::kind` to `AssocTag`. Removed `find_by_name_and_kinds`, which is unused. `AssocItem::descr` can now distinguish between methods and associated functions, which slightly improves some error messages.
2025-04-14Raise errors on bad rustc_on_unimplemented format strings againmejrs-3/+35
2025-04-14Disable usage on trait impls and aliasesmejrs-4/+13
2025-04-14Documentation and finishing touchesmejrs-79/+196
2025-04-11`NonGenericOpaqueTypeParam::ty` to `arg`lcnr-2/+2
2025-04-11Rollup merge of #139564 - compiler-errors:deeply-norm, r=lcnrStuart Cook-48/+55
Deeply normalize obligations in `BestObligation` folder Built on #139513. This establishes a somewhat rough invariant that the `Obligation`'s predicate is always deeply normalized in the folder; when we construct a new obligation we normalize it. Putting this up for discussion since it does affect some goals. r? lcnr
2025-04-11Rollup merge of #138998 - ↵Stuart Cook-6/+17
rperier:donot_suggest_to_use_impl_trait_in_closure_params, r=Noratrieb Don't suggest the use of `impl Trait` in closure parameter Fixes #138932
2025-04-10Deeply normalize obligations in BestObligationMichael Goulet-18/+33
2025-04-10SimplifyMichael Goulet-30/+22
2025-04-10Parse condition options into a structmejrs-165/+168
2025-04-10Write the format string parserand split it from conditions parsermejrs-280/+528
2025-04-10Rollup merge of #139510 - nnethercote:name-to-ident, r=fee1-deadMatthias Krüger-2/+2
Rename some `name` variables as `ident`. It bugs me when variables of type `Ident` are called `name`. It leads to silly things like `name.name`. `Ident` variables should be called `ident`, and `name` should be used for variables of type `Symbol`. This commit improves things by by doing `s/name/ident/` on a bunch of `Ident` variables. Not all of them, but a decent chunk. r? `@fee1-dead`
2025-04-10Auto merge of #139000 - compiler-errors:rigid-missing-item, r=lcnrbors-45/+45
Rigidly project missing item due to guaranteed impossible sized predicate This is a somewhat involved change, but it amounts to treating missing impl items due to guaranteed impossible where clauses (dyn/str/slice sized, cc #135480) as *rigid projections* rather than projecting to an error term, since that was preventing either reporting a proper error (in an empty param env) *or* successfully type checking the code (in the presence of trivially false where clauses). Fixes https://github.com/rust-lang/rust/issues/138970 r? `@lcnr` `@oli-obk`
2025-04-10Rename some `name` variables as `ident`.Nicholas Nethercote-2/+2
It bugs me when variables of type `Ident` are called `name`. It leads to silly things like `name.name`. `Ident` variables should be called `ident`, and `name` should be used for variables of type `Symbol`. This commit improves things by by doing `s/name/ident/` on a bunch of `Ident` variables. Not all of them, but a decent chunk.
2025-04-09Use a query rather than recomputing the tail repeatedlyMichael Goulet-15/+1
2025-04-09Rigidly project missing item due to guaranteed impossible sized predicateMichael Goulet-45/+59
2025-04-09Move errorsmejrs-77/+89
2025-04-09Report higher-ranked trait error when higher-ranked projection goal fails in ↵Michael Goulet-3/+33
new solver
2025-04-09re-use sized fast pathDavid Wood-15/+35
There's an existing fast path for the `type_op_prove_predicate` predicate, checking for trivially `Sized` types, which can be re-used when evaluating obligations within queries. This should improve performance, particularly in anticipation of new sizedness traits being added which can take advantage of this.
2025-04-09Suggest the use of `impl Trait` in function parameter onlyRomain Perier-6/+17
Currently in case of a Trait object in closure parameter, the compiler suggests either to use a reference, which is correct or to use an `impl Trait` which is not. Do not emit this suggestion when the parameter is part of a closure.
2025-04-09Auto merge of #139552 - matthiaskrgr:rollup-b194mk8, r=matthiaskrgrbors-30/+56
Rollup of 10 pull requests Successful merges: - #139494 (Restrict some queries by def-kind more) - #139496 (Revert r-a changes of rust-lang/rust#139455) - #139506 (add missing word in doc comment (part 2)) - #139515 (Improve presentation of closure signature mismatch from `Fn` trait goal) - #139520 (compiletest maintenance: sort deps and drop dep on `anyhow`) - #139523 (Rustc dev guide subtree update) - #139526 (Fix deprecation note for std::intrinsics) - #139528 (compiletest: Remove the `--logfile` flag) - #139541 (Instantiate higher-ranked transmute goal w/ placeholders before emitting sub-obligations) - #139547 (Update library tracking issue template to set S-tracking-unimplemented) r? `@ghost` `@rustbot` modify labels: rollup
2025-04-08Rollup merge of #139541 - compiler-errors:transmute, r=lcnrMatthias Krüger-3/+3
Instantiate higher-ranked transmute goal w/ placeholders before emitting sub-obligations This avoids an ICE where we weren't keeping track of bound variables correctly in the `Freeze` obligations we emit for transmute goals. We could use `rebind` instead on that goal, but I think it's better just to instantiate the binder. Fixes #139538 r? `@lcnr` or reassign
2025-04-08Rollup merge of #139515 - compiler-errors:sig-mismatch, r=lcnrMatthias Krüger-27/+53
Improve presentation of closure signature mismatch from `Fn` trait goal Flip the order of "expected" and "found" since that wasn't correct. Don't present the arguments as a tuple, since it leaves a trailing comma. Instead, just use `fn(arg, arg)`. Finally, be better with binders since we were just skipping binders. r? oli-obk or reassign
2025-04-08Instantiate higher-ranked transmute goalMichael Goulet-3/+3
2025-04-08Rollup merge of #139509 - xizheyin:issue-139359, r=lcnrMatthias Krüger-15/+15
clean: remove Deref<Target=RegionKind> impl for Region and use `.kind()` Closes #139359 r? `@lcnr`
2025-04-08Remove unnecessary dyn Display in favor of strMichael Goulet-4/+4
2025-04-08Improve presentation of closure signature mismatch from Fn trait goalMichael Goulet-25/+51
2025-04-08clean code: remove Deref<Target=RegionKind> impl for Region and use `.kind()`xizheyin-15/+15
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-04-05Fix trait upcasting to dyn type with no principal when there are projectionsMichael Goulet-14/+24
2025-04-04Auto merge of #138785 - lcnr:typing-mode-borrowck, r=compiler-errors,oli-obkbors-2/+203
add `TypingMode::Borrowck` Shares the first commit with #138499, doesn't really matter which PR to land first :blush: :grin: Introduces `TypingMode::Borrowck` which unlike `TypingMode::Analysis`, uses the hidden type computed by HIR typeck as the initial value of opaques instead of an unconstrained infer var. This is a part of https://github.com/rust-lang/types-team/issues/129. Using this new `TypingMode` is unfortunately a breaking change for now, see tests/ui/impl-trait/non-defining-uses/as-projection-term.rs. Using an inference variable as the initial value results in non-defining uses in the defining scope. We therefore only enable it if with `-Znext-solver=globally` or `-Ztyping-mode-borrowck` To do that the PR contains the following changes: - `TypeckResults::concrete_opaque_type` are already mapped to the definition of the opaque type - writeback now checks that the non-lifetime parameters of the opaque are universal - for this, `fn check_opaque_type_parameter_valid` is moved from `rustc_borrowck` to `rustc_trait_selection` - we add a new `query type_of_opaque_hir_typeck` which, using the same visitors as MIR typeck, attempts to merge the hidden types from HIR typeck from all defining scopes - done by adding a `DefiningScopeKind` flag to toggle between using borrowck and HIR typeck - the visitors stop checking that the MIR type matches the HIR type. This is trivial as the HIR type are now used as the initial hidden types of the opaque. This check is useful as a safeguard when not using `TypingMode::Borrowck`, but adding it to the new structure is annoying and it's not soundness critical, so I intend to not add it back. - add a `TypingMode::Borrowck` which behaves just like `TypingMode::Analysis` except when normalizing opaque types - it uses `type_of_opaque_hir_typeck(opaque)` as the initial value after replacing its regions with new inference vars - it uses structural lookup in the new solver fixes #112201, fixes #132335, fixes #137751 r? `@compiler-errors` `@oli-obk`
2025-04-04Rollup merge of #139335 - compiler-errors:error-implies, r=oli-obkMatthias Krüger-28/+32
Pass correct param-env to `error_implies` Duplicated comment from the test: In the error reporting code, when reporting fulfillment errors for goals A and B, we try to see if elaborating A will result in another goal that can equate with B. That would signal that B is "implied by" A, allowing us to skip reporting it, which is beneficial for cutting down on the number of diagnostics we report. In the new trait solver especially, but even in the old trait solver through things like defining opaque type usages, this `can_equate` call was not properly taking the param-env of the goals, resulting in nested obligations that had empty param-envs. If one of these nested obligations was a `ConstParamHasTy` goal, then we would ICE, since those goals are particularly strict about the param-env they're evaluated in. This is morally a fix for <https://github.com/rust-lang/rust/issues/139314>, but that repro uses details about how defining usages in the `check_opaque_well_formed` code can spring out of type equality, and will likely stop failing soon coincidentally once we start using `PostBorrowck` mode in that check. Instead, we use lazy normalization to end up generating an alias-eq goal whose nested goals woul trigger the ICE instead, since this is a lot more stable. Fixes https://github.com/rust-lang/rust/issues/139314 r? ``@oli-obk`` or reassign
2025-04-04Auto merge of #120706 - Bryanskiy:leak, r=lcnrbors-15/+29
Initial support for auto traits with default bounds This PR is part of ["MCP: Low level components for async drop"](https://github.com/rust-lang/compiler-team/issues/727) Tracking issue: #138781 Summary: https://github.com/rust-lang/rust/pull/120706#issuecomment-1934006762 ### Intro Sometimes we want to use type system to express specific behavior and provide safety guarantees. This behavior can be specified by various "marker" traits. For example, we use `Send` and `Sync` to keep track of which types are thread safe. As the language develops, there are more problems that could be solved by adding new marker traits: - to forbid types with an async destructor to be dropped in a synchronous context a trait like `SyncDrop` could be used [Async destructors, async genericity and completion futures](https://sabrinajewson.org/blog/async-drop). - to support [scoped tasks](https://without.boats/blog/the-scoped-task-trilemma/) or in a more general sense to provide a [destruction guarantee](https://zetanumbers.github.io/book/myosotis.html) there is a desire among some users to see a `Leak` (or `Forget`) trait. - Withoutboats in his [post](https://without.boats/blog/changing-the-rules-of-rust/) reflected on the use of `Move` trait instead of a `Pin`. All the traits proposed above are supposed to be auto traits implemented for most types, and usually implemented automatically by compiler. For backward compatibility these traits have to be added implicitly to all bound lists in old code (see below). Adding new default bounds involves many difficulties: many standard library interfaces may need to opt out of those default bounds, and therefore be infected with confusing `?Trait` syntax, migration to a new edition may contain backward compatibility holes, supporting new traits in the compiler can be quite difficult and so forth. Anyway, it's hard to evaluate the complexity until we try the system on a practice. In this PR we introduce new optional lang items for traits that are added to all bound lists by default, similarly to existing `Sized`. The examples of such traits could be `Leak`, `Move`, `SyncDrop` or something else, it doesn't matter much right now (further I will call them `DefaultAutoTrait`'s). We want to land this change into rustc under an option, so it becomes available in bootstrap compiler. Then we'll be able to do standard library experiments with the aforementioned traits without adding hundreds of `#[cfg(not(bootstrap))]`s. Based on the experiments, we can come up with some scheme for the next edition, in which such bounds are added in a more targeted way, and not just everywhere. Most of the implementation is basically a refactoring that replaces hardcoded uses of `Sized` with iterating over a list of traits including both `Sized` and the new traits when `-Zexperimental-default-bounds` is enabled (or just `Sized` as before, if the option is not enabled). ### Default bounds for old editions All existing types, including generic parameters, are considered `Leak`/`Move`/`SyncDrop` and can be forgotten, moved or destroyed in generic contexts without specifying any bounds. New types that cannot be, for example, forgotten and do not implement `Leak` can be added at some point, and they should not be usable in such generic contexts in existing code. To both maintain this property and keep backward compatibility with existing code, the new traits should be added as default bounds _everywhere_ in previous editions. Besides the implicit `Sized` bound contexts that includes supertrait lists and trait lists in trait objects (`dyn Trait1 + ... + TraitN`). Compiler should also generate implicit `DefaultAutoTrait` implementations for foreign types (`extern { type Foo; }`) because they are also currently usable in generic contexts without any bounds. #### Supertraits Adding the new traits as supertraits to all existing traits is potentially necessary, because, for example, using a `Self` param in a trait's associated item may be a breaking change otherwise: ```rust trait Foo: Sized { fn new() -> Option<Self>; // ERROR: `Option` requires `DefaultAutoTrait`, but `Self` is not `DefaultAutoTrait` } // desugared `Option` enum Option<T: DefaultAutoTrait + Sized> { Some(T), None, } ``` However, default supertraits can significantly affect compiler performance. For example, if we know that `T: Trait`, the compiler would deduce that `T: DefaultAutoTrait`. It also implies proving `F: DefaultAutoTrait` for each field `F` of type `T` until an explicit impl is be provided. If the standard library is not modified, then even traits like `Copy` or `Send` would get these supertraits. In this PR for optimization purposes instead of adding default supertraits, bounds are added to the associated items: ```rust // Default bounds are generated in the following way: trait Trait { fn foo(&self) where Self: DefaultAutoTrait {} } // instead of this: trait Trait: DefaultAutoTrait { fn foo(&self) {} } ``` It is not always possible to do this optimization because of backward compatibility: ```rust pub trait Trait<Rhs = Self> {} pub trait Trait1 : Trait {} // ERROR: `Rhs` requires `DefaultAutoTrait`, but `Self` is not `DefaultAutoTrait` ``` or ```rust trait Trait { type Type where Self: Sized; } trait Trait2<T> : Trait<Type = T> {} // ERROR: `???` requires `DefaultAutoTrait`, but `Self` is not `DefaultAutoTrait` ``` Therefore, `DefaultAutoTrait`'s are still being added to supertraits if the `Self` params or type bindings were found in the trait header. #### Trait objects Trait objects requires explicit `+ Trait` bound to implement corresponding trait which is not backward compatible: ```rust fn use_trait_object(x: Box<dyn Trait>) { foo(x) // ERROR: `foo` requires `DefaultAutoTrait`, but `dyn Trait` is not `DefaultAutoTrait` } // implicit T: DefaultAutoTrait here fn foo<T>(_: T) {} ``` So, for a trait object `dyn Trait` we should add an implicit bound `dyn Trait + DefaultAutoTrait` to make it usable, and allow relaxing it with a question mark syntax `dyn Trait + ?DefaultAutoTrait` when it's not necessary. #### Foreign types If compiler doesn't generate auto trait implementations for a foreign type, then it's a breaking change if the default bounds are added everywhere else: ```rust // implicit T: DefaultAutoTrait here fn foo<T: ?Sized>(_: &T) {} extern "C" { type ExternTy; } fn forward_extern_ty(x: &ExternTy) { foo(x); // ERROR: `foo` requires `DefaultAutoTrait`, but `ExternTy` is not `DefaultAutoTrait` } ``` We'll have to enable implicit `DefaultAutoTrait` implementations for foreign types at least for previous editions: ```rust // implicit T: DefaultAutoTrait here fn foo<T: ?Sized>(_: &T) {} extern "C" { type ExternTy; } impl DefaultAutoTrait for ExternTy {} // implicit impl fn forward_extern_ty(x: &ExternTy) { foo(x); // OK } ``` ### Unresolved questions New default bounds affect all existing Rust code complicating an already complex type system. - Proving an auto trait predicate requires recursively traversing the type and proving the predicate for it's fields. This leads to a significant performance regression. Measurements for the stage 2 compiler build show up to 3x regression. - We hope that fast path optimizations for well known traits could mitigate such regressions at least partially. - New default bounds trigger some compiler bugs in both old and new trait solver. - With new default bounds we encounter some trait solver cycle errors that break existing code. - We hope that these cases are bugs that can be addressed in the new trait solver. Also migration to a new edition could be quite ugly and enormous, but that's actually what we want to solve. For other issues there's a chance that they could be solved by a new solver.
2025-04-03Pass correct param-env to error_impliesMichael Goulet-28/+32
2025-04-03Initial support for auto traits with default boundsBryanskiy-15/+29
2025-04-03add `TypingMode::Borrowck`lcnr-6/+30
2025-04-03move `check_opaque_type_parameter_valid`lcnr-1/+178
2025-04-02Rollup merge of #139232 - nnethercote:remove-Map-5, r=ZalatharTakayuki Maeda-15/+13
Move methods from `Map` to `TyCtxt`, part 5. This eliminates all methods on `Map`. Actually removing `Map` will occur in a follow-up PR. A follow-up to #137504. r? `@Zalathar`
2025-04-02Auto merge of #139018 - oli-obk:incremental-trait-impls, r=compiler-errorsbors-2/+2
Various local trait item iteration cleanups Adding a trait impl for `Foo` unconditionally affected all queries that are interested in a completely independent trait `Bar`. Perf has no effect on this. We probably don't have a good perf test for this tho. r? `@compiler-errors` I am unsure about https://github.com/rust-lang/rust/pull/139018/commits/9d05efb66f7b599eeacb5d2456f844fe4768e865 as it doesn't improve anything wrt incremental, because we still do all the checks for valid `Drop` impls, which subsequently will still invoke many queries and basically keep the depgraph the same. I want to do https://github.com/rust-lang/rust/blob/9549077a47099dc826039c051b528d1013740e6f/compiler/rustc_middle/src/ty/trait_def.rs#L141 but would leave that to a follow-up PR, this one changes enough things as it is
2025-04-02Remove a `hir_*` helper that was just forwarding to a queryOli Scherer-1/+1