From ac159dd9bd2fbec369d5231c49a068c343737dee Mon Sep 17 00:00:00 2001 From: Muhtasim-Rasheed Date: Sun, 1 Feb 2026 19:01:19 +0600 Subject: [PATCH 01/11] Add help message suggesting explicit reference cast for From/TryFrom Make fmt check happy --- .../traits/fulfillment_errors.rs | 85 +++++++++++++++++++ tests/ui/traits/explicit-reference-cast.rs | 50 +++++++++++ .../ui/traits/explicit-reference-cast.stderr | 68 +++++++++++++++ 3 files changed, 203 insertions(+) create mode 100644 tests/ui/traits/explicit-reference-cast.rs create mode 100644 tests/ui/traits/explicit-reference-cast.stderr diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 6872d038fb7f0..d888c767203aa 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -277,6 +277,28 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }; let mut err = struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg); + + let trait_def_id = main_trait_predicate.def_id(); + if self.tcx.is_diagnostic_item(sym::From, trait_def_id) + || self.tcx.is_diagnostic_item(sym::TryFrom, trait_def_id) + { + let found_ty = leaf_trait_predicate.skip_binder().trait_ref.args.type_at(1); + let ty = main_trait_predicate.skip_binder().self_ty(); + if let Some(cast_ty) = self.find_explicit_cast_type( + obligation.param_env, + found_ty, + ty, + ) { + let found_ty_str = self.tcx.short_string(found_ty, &mut long_ty_file); + let cast_ty_str = self.tcx.short_string(cast_ty, &mut long_ty_file); + err.help( + format!( + "consider casting the `{found_ty_str}` value to `{cast_ty_str}`", + ), + ); + } + } + *err.long_ty_path() = long_ty_file; let mut suggested = false; @@ -2930,6 +2952,69 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }) } + /// If `found_ty` is a reference that can be explicitly cast to another reference type for which + /// a `From` / `TryFrom` impl exists for `self_ty`, return that type. + fn find_explicit_cast_type( + &self, + param_env: ty::ParamEnv<'tcx>, + found_ty: Ty<'tcx>, + self_ty: Ty<'tcx>, + ) -> Option> { + let ty::Ref(region, inner_ty, mutbl) = *found_ty.kind() else { + return None; + }; + + let mut derefs = (self.autoderef_steps)(inner_ty).into_iter(); + derefs.next(); // skip the first one, which is inner_ty itself + let deref_target = derefs.into_iter().next()?.0; + + let cast_ty = Ty::new_ref(self.tcx, region, deref_target, mutbl); + + let Some(from_def_id) = self.tcx.get_diagnostic_item(sym::From) else { + return None; + }; + let Some(try_from_def_id) = self.tcx.get_diagnostic_item(sym::TryFrom) else { + return None; + }; + + if self.has_impl_for_type( + param_env, + ty::TraitRef::new( + self.tcx, + from_def_id, + self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]), + ), + ) { + Some(cast_ty) + } else if self.has_impl_for_type( + param_env, + ty::TraitRef::new( + self.tcx, + try_from_def_id, + self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]), + ), + ) { + Some(cast_ty) + } else { + None + } + } + + fn has_impl_for_type( + &self, + param_env: ty::ParamEnv<'tcx>, + trait_ref: ty::TraitRef<'tcx>, + ) -> bool { + let obligation = Obligation::new( + self.tcx, + ObligationCause::dummy(), + param_env, + ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive }, + ); + + self.predicate_must_hold_modulo_regions(&obligation) + } + fn add_tuple_trait_message( &self, obligation_cause_code: &ObligationCauseCode<'tcx>, diff --git a/tests/ui/traits/explicit-reference-cast.rs b/tests/ui/traits/explicit-reference-cast.rs new file mode 100644 index 0000000000000..efb4f10bea67e --- /dev/null +++ b/tests/ui/traits/explicit-reference-cast.rs @@ -0,0 +1,50 @@ +// compile-fail + +use std::convert::TryFrom; +use std::path::{Path, PathBuf}; + +pub struct ToolA(PathBuf); +//~^ HELP the trait `From<&PathBuf>` is not implemented for `ToolA` + +impl From<&Path> for ToolA { + //~^ HELP the following other types implement trait `From` + fn from(p: &Path) -> ToolA { + ToolA(p.to_path_buf()) + } +} + +// Add a different From impl to ensure we suggest the correct cast +impl From<&str> for ToolA { + fn from(s: &str) -> ToolA { + ToolA(PathBuf::from(s)) + } +} + +pub struct ToolB(PathBuf); +//~^ HELP the trait `From<&PathBuf>` is not implemented for `ToolB` +//~| HELP the trait `From<&PathBuf>` is not implemented for `ToolB` + +impl TryFrom<&Path> for ToolB { + //~^ HELP the trait `TryFrom<&PathBuf>` is not implemented for `ToolB` + //~| HELP the trait `TryFrom<&PathBuf>` is not implemented for `ToolB` + type Error = (); + + fn try_from(p: &Path) -> Result { + Ok(ToolB(p.to_path_buf())) + } +} + +fn main() { + let path = PathBuf::new(); + + let _ = ToolA::from(&path); + //~^ ERROR the trait bound `ToolA: From<&PathBuf>` is not satisfied + //~| HELP consider casting the `&PathBuf` value to `&Path` + let _ = ToolB::try_from(&path); + //~^ ERROR the trait bound `ToolB: TryFrom<&PathBuf>` is not satisfied + //~| ERROR the trait bound `ToolB: From<&PathBuf>` is not satisfied + //~| HELP consider casting the `&PathBuf` value to `&Path` + //~| HELP consider casting the `&PathBuf` value to `&Path` + //~| HELP for that trait implementation, expected `Path`, found `PathBuf` + //~| HELP for that trait implementation, expected `Path`, found `PathBuf` +} diff --git a/tests/ui/traits/explicit-reference-cast.stderr b/tests/ui/traits/explicit-reference-cast.stderr new file mode 100644 index 0000000000000..924de3d5bbe3b --- /dev/null +++ b/tests/ui/traits/explicit-reference-cast.stderr @@ -0,0 +1,68 @@ +error[E0277]: the trait bound `ToolA: From<&PathBuf>` is not satisfied + --> $DIR/explicit-reference-cast.rs:40:13 + | +LL | let _ = ToolA::from(&path); + | ^^^^^ unsatisfied trait bound + | + = help: consider casting the `&PathBuf` value to `&Path` +help: the trait `From<&PathBuf>` is not implemented for `ToolA` + --> $DIR/explicit-reference-cast.rs:6:1 + | +LL | pub struct ToolA(PathBuf); + | ^^^^^^^^^^^^^^^^ +help: the following other types implement trait `From` + --> $DIR/explicit-reference-cast.rs:9:1 + | +LL | impl From<&Path> for ToolA { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ `ToolA` implements `From<&Path>` +... +LL | impl From<&str> for ToolA { + | ^^^^^^^^^^^^^^^^^^^^^^^^^ `ToolA` implements `From<&str>` + +error[E0277]: the trait bound `ToolB: TryFrom<&PathBuf>` is not satisfied + --> $DIR/explicit-reference-cast.rs:43:13 + | +LL | let _ = ToolB::try_from(&path); + | ^^^^^ unsatisfied trait bound + | + = help: consider casting the `&PathBuf` value to `&Path` +help: the trait `From<&PathBuf>` is not implemented for `ToolB` + --> $DIR/explicit-reference-cast.rs:23:1 + | +LL | pub struct ToolB(PathBuf); + | ^^^^^^^^^^^^^^^^ +help: the trait `TryFrom<&PathBuf>` is not implemented for `ToolB` + but trait `TryFrom<&Path>` is implemented for it + --> $DIR/explicit-reference-cast.rs:27:1 + | +LL | impl TryFrom<&Path> for ToolB { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `Path`, found `PathBuf` + = note: required for `&PathBuf` to implement `Into` + = note: required for `ToolB` to implement `TryFrom<&PathBuf>` + +error[E0277]: the trait bound `ToolB: From<&PathBuf>` is not satisfied + --> $DIR/explicit-reference-cast.rs:43:13 + | +LL | let _ = ToolB::try_from(&path); + | ^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: consider casting the `&PathBuf` value to `&Path` +help: the trait `From<&PathBuf>` is not implemented for `ToolB` + --> $DIR/explicit-reference-cast.rs:23:1 + | +LL | pub struct ToolB(PathBuf); + | ^^^^^^^^^^^^^^^^ +help: the trait `TryFrom<&PathBuf>` is not implemented for `ToolB` + but trait `TryFrom<&Path>` is implemented for it + --> $DIR/explicit-reference-cast.rs:27:1 + | +LL | impl TryFrom<&Path> for ToolB { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `Path`, found `PathBuf` + = note: required for `&PathBuf` to implement `Into` + = note: required for `ToolB` to implement `TryFrom<&PathBuf>` + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0277`. From dc24aae43e6e1751c498df619ca572eaa7adf4a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Thu, 29 Jan 2026 21:13:09 +0100 Subject: [PATCH 02/11] Modernize diagnostic for indeterminate trait object lifetime bounds --- compiler/rustc_hir_analysis/src/collect.rs | 32 +++++++++++-------- .../src/hir_ty_lowering/dyn_trait.rs | 2 +- .../src/hir_ty_lowering/mod.rs | 2 +- .../object-lifetime-default-ambiguous.rs | 6 ++-- .../object-lifetime-default-ambiguous.stderr | 21 ++++++++++-- ...lifetime-default-dyn-binding-nonstatic1.rs | 2 +- ...time-default-dyn-binding-nonstatic1.stderr | 7 +++- ...lifetime-default-dyn-binding-nonstatic2.rs | 2 +- ...time-default-dyn-binding-nonstatic2.stderr | 7 +++- ...lifetime-default-dyn-binding-nonstatic3.rs | 2 +- ...time-default-dyn-binding-nonstatic3.stderr | 7 +++- 11 files changed, 63 insertions(+), 27 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index dd399f9d90def..919199f0b573c 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -22,9 +22,7 @@ use rustc_abi::{ExternAbi, Size}; use rustc_ast::Recovered; use rustc_data_structures::assert_matches; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; -use rustc_errors::{ - Applicability, Diag, DiagCtxtHandle, E0228, ErrorGuaranteed, StashKey, struct_span_code_err, -}; +use rustc_errors::{Applicability, Diag, DiagCtxtHandle, E0228, ErrorGuaranteed, StashKey}; use rustc_hir::attrs::AttributeKind; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -316,16 +314,24 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> { } fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx> { - if let RegionInferReason::ObjectLifetimeDefault = reason { - let e = struct_span_code_err!( - self.dcx(), - span, - E0228, - "the lifetime bound for this object type cannot be deduced \ - from context; please supply an explicit bound" - ) - .emit(); - ty::Region::new_error(self.tcx(), e) + if let RegionInferReason::ObjectLifetimeDefault(sugg_sp) = reason { + // FIXME: Account for trailing plus `dyn Trait+`, the need of parens in + // `*const dyn Trait` and `Fn() -> *const dyn Trait`. + let guar = self + .dcx() + .struct_span_err( + span, + "cannot deduce the lifetime bound for this trait object type from context", + ) + .with_code(E0228) + .with_span_suggestion_verbose( + sugg_sp, + "please supply an explicit bound", + " + /* 'a */", + Applicability::HasPlaceholders, + ) + .emit(); + ty::Region::new_error(self.tcx(), guar) } else { // This indicates an illegal lifetime in a non-assoc-trait position ty::Region::new_error_with_message(self.tcx(), span, "unelided lifetime in signature") diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs index 29f29761b6055..37a9f41e8942d 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_trait.rs @@ -460,7 +460,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // Parent lifetime must have failed to resolve. Don't emit a redundant error. RegionInferReason::ExplicitObjectLifetime } else { - RegionInferReason::ObjectLifetimeDefault + RegionInferReason::ObjectLifetimeDefault(span.shrink_to_hi()) } } else { RegionInferReason::ExplicitObjectLifetime diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index 867c588e302d3..ccccb6145c46d 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -105,7 +105,7 @@ pub enum RegionInferReason<'a> { /// Lifetime on a trait object that is spelled explicitly, e.g. `+ 'a` or `+ '_`. ExplicitObjectLifetime, /// A trait object's lifetime when it is elided, e.g. `dyn Any`. - ObjectLifetimeDefault, + ObjectLifetimeDefault(Span), /// Generic lifetime parameter Param(&'a ty::GenericParamDef), RegionPredicate, diff --git a/tests/ui/object-lifetime/object-lifetime-default-ambiguous.rs b/tests/ui/object-lifetime/object-lifetime-default-ambiguous.rs index 5dae92fee5f90..0a0f44073740e 100644 --- a/tests/ui/object-lifetime/object-lifetime-default-ambiguous.rs +++ b/tests/ui/object-lifetime/object-lifetime-default-ambiguous.rs @@ -21,11 +21,11 @@ struct Ref2<'a,'b:'a,T:'a+'b+?Sized> { } fn a<'a,'b>(t: Ref2<'a,'b, dyn Test>) { - //~^ ERROR lifetime bound for this object type cannot be deduced from context + //~^ ERROR cannot deduce the lifetime bound for this trait object type } fn b(t: Ref2) { - //~^ ERROR lifetime bound for this object type cannot be deduced from context + //~^ ERROR cannot deduce the lifetime bound for this trait object type } fn c(t: Ref2<&dyn Test>) { @@ -41,7 +41,7 @@ fn e(t: Ref2>) { } fn f(t: &Ref2) { - //~^ ERROR lifetime bound for this object type cannot be deduced from context + //~^ ERROR cannot deduce the lifetime bound for this trait object type } fn main() { diff --git a/tests/ui/object-lifetime/object-lifetime-default-ambiguous.stderr b/tests/ui/object-lifetime/object-lifetime-default-ambiguous.stderr index bd50a27fd5e58..6aa3da66fda0f 100644 --- a/tests/ui/object-lifetime/object-lifetime-default-ambiguous.stderr +++ b/tests/ui/object-lifetime/object-lifetime-default-ambiguous.stderr @@ -1,20 +1,35 @@ -error[E0228]: the lifetime bound for this object type cannot be deduced from context; please supply an explicit bound +error[E0228]: cannot deduce the lifetime bound for this trait object type from context --> $DIR/object-lifetime-default-ambiguous.rs:23:28 | LL | fn a<'a,'b>(t: Ref2<'a,'b, dyn Test>) { | ^^^^^^^^ + | +help: please supply an explicit bound + | +LL | fn a<'a,'b>(t: Ref2<'a,'b, dyn Test + /* 'a */>) { + | ++++++++++ -error[E0228]: the lifetime bound for this object type cannot be deduced from context; please supply an explicit bound +error[E0228]: cannot deduce the lifetime bound for this trait object type from context --> $DIR/object-lifetime-default-ambiguous.rs:27:14 | LL | fn b(t: Ref2) { | ^^^^^^^^ + | +help: please supply an explicit bound + | +LL | fn b(t: Ref2) { + | ++++++++++ -error[E0228]: the lifetime bound for this object type cannot be deduced from context; please supply an explicit bound +error[E0228]: cannot deduce the lifetime bound for this trait object type from context --> $DIR/object-lifetime-default-ambiguous.rs:43:15 | LL | fn f(t: &Ref2) { | ^^^^^^^^ + | +help: please supply an explicit bound + | +LL | fn f(t: &Ref2) { + | ++++++++++ error: aborting due to 3 previous errors diff --git a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic1.rs b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic1.rs index 7337383e29784..7a7bba02879ec 100644 --- a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic1.rs +++ b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic1.rs @@ -18,7 +18,7 @@ fn is_static(_: T) where T: 'static { } // Here, we should default to `dyn Bar + 'static`, but the current // code forces us into a conservative, hacky path. fn bar<'a>(x: &'a str) -> &'a dyn Foo<'a, Item = dyn Bar> { &() } -//~^ ERROR please supply an explicit bound +//~^ ERROR cannot deduce the lifetime bound for this trait object type fn main() { let s = format!("foo"); diff --git a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic1.stderr b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic1.stderr index 8d44b4de55a47..5744d0dd162cd 100644 --- a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic1.stderr +++ b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic1.stderr @@ -1,8 +1,13 @@ -error[E0228]: the lifetime bound for this object type cannot be deduced from context; please supply an explicit bound +error[E0228]: cannot deduce the lifetime bound for this trait object type from context --> $DIR/object-lifetime-default-dyn-binding-nonstatic1.rs:20:50 | LL | fn bar<'a>(x: &'a str) -> &'a dyn Foo<'a, Item = dyn Bar> { &() } | ^^^^^^^ + | +help: please supply an explicit bound + | +LL | fn bar<'a>(x: &'a str) -> &'a dyn Foo<'a, Item = dyn Bar + /* 'a */> { &() } + | ++++++++++ error: aborting due to 1 previous error diff --git a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic2.rs b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic2.rs index 2a7415174f8a0..9ddf792eaada4 100644 --- a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic2.rs +++ b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic2.rs @@ -18,7 +18,7 @@ fn is_static(_: T) where T: 'static { } // Here, we default to `dyn Bar + 'a`. Or, we *should*, but the // current code forces us into a conservative, hacky path. fn bar<'a>(x: &'a str) -> &'a dyn Foo<'a, Item = dyn Bar> { &() } -//~^ ERROR please supply an explicit bound +//~^ ERROR cannot deduce the lifetime bound for this trait object type fn main() { let s = format!("foo"); diff --git a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic2.stderr b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic2.stderr index 0846dd60723a4..ca8612f57934e 100644 --- a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic2.stderr +++ b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic2.stderr @@ -1,8 +1,13 @@ -error[E0228]: the lifetime bound for this object type cannot be deduced from context; please supply an explicit bound +error[E0228]: cannot deduce the lifetime bound for this trait object type from context --> $DIR/object-lifetime-default-dyn-binding-nonstatic2.rs:20:50 | LL | fn bar<'a>(x: &'a str) -> &'a dyn Foo<'a, Item = dyn Bar> { &() } | ^^^^^^^ + | +help: please supply an explicit bound + | +LL | fn bar<'a>(x: &'a str) -> &'a dyn Foo<'a, Item = dyn Bar + /* 'a */> { &() } + | ++++++++++ error: aborting due to 1 previous error diff --git a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic3.rs b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic3.rs index 51be999a6329d..48ac5623f898b 100644 --- a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic3.rs +++ b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic3.rs @@ -14,7 +14,7 @@ fn is_static(_: T) where T: 'static { } // Here, we should default to `dyn Bar + 'static`, but the current // code forces us into a conservative, hacky path. fn bar(x: &str) -> &dyn Foo { &() } -//~^ ERROR please supply an explicit bound +//~^ ERROR cannot deduce the lifetime bound for this trait object type fn main() { let s = format!("foo"); diff --git a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic3.stderr b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic3.stderr index 688f8af0822b4..05620d3878f75 100644 --- a/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic3.stderr +++ b/tests/ui/object-lifetime/object-lifetime-default-dyn-binding-nonstatic3.stderr @@ -1,8 +1,13 @@ -error[E0228]: the lifetime bound for this object type cannot be deduced from context; please supply an explicit bound +error[E0228]: cannot deduce the lifetime bound for this trait object type from context --> $DIR/object-lifetime-default-dyn-binding-nonstatic3.rs:16:36 | LL | fn bar(x: &str) -> &dyn Foo { &() } | ^^^^^^^ + | +help: please supply an explicit bound + | +LL | fn bar(x: &str) -> &dyn Foo { &() } + | ++++++++++ error: aborting due to 1 previous error From 03dcd99aa322a0d5c9b5f203b1222798bbabf941 Mon Sep 17 00:00:00 2001 From: ia0 Date: Sat, 7 Feb 2026 15:39:42 +0100 Subject: [PATCH 03/11] Format heterogeneous try blocks --- src/tools/rustfmt/src/expr.rs | 29 +++++++++++++-- .../tests/source/try_blocks_heterogeneous.rs | 34 ++++++++++++++++++ .../tests/target/try_blocks_heterogeneous.rs | 36 +++++++++++++++++++ 3 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 src/tools/rustfmt/tests/source/try_blocks_heterogeneous.rs create mode 100644 src/tools/rustfmt/tests/target/try_blocks_heterogeneous.rs diff --git a/src/tools/rustfmt/src/expr.rs b/src/tools/rustfmt/src/expr.rs index de96f004dc873..70bce1920047f 100644 --- a/src/tools/rustfmt/src/expr.rs +++ b/src/tools/rustfmt/src/expr.rs @@ -385,8 +385,33 @@ pub(crate) fn format_expr( )) } } - // FIXME: heterogeneous try blocks, which include a type so are harder to format - ast::ExprKind::TryBlock(_, Some(_)) => Err(RewriteError::Unknown), + ast::ExprKind::TryBlock(ref block, Some(ref ty)) => { + let keyword = "try bikeshed "; + // 2 = " {".len() + let ty_shape = shape + .shrink_left(keyword.len()) + .and_then(|shape| shape.sub_width(2)) + .max_width_error(shape.width, expr.span)?; + let ty_str = ty.rewrite_result(context, ty_shape)?; + let prefix = format!("{keyword}{ty_str} "); + if let rw @ Ok(_) = + rewrite_single_line_block(context, &prefix, block, Some(&expr.attrs), None, shape) + { + rw + } else { + let budget = shape.width.saturating_sub(prefix.len()); + Ok(format!( + "{prefix}{}", + rewrite_block( + block, + Some(&expr.attrs), + None, + context, + Shape::legacy(budget, shape.indent) + )? + )) + } + } ast::ExprKind::Gen(capture_by, ref block, ref kind, _) => { let mover = if matches!(capture_by, ast::CaptureBy::Value { .. }) { "move " diff --git a/src/tools/rustfmt/tests/source/try_blocks_heterogeneous.rs b/src/tools/rustfmt/tests/source/try_blocks_heterogeneous.rs new file mode 100644 index 0000000000000..bae0060374d88 --- /dev/null +++ b/src/tools/rustfmt/tests/source/try_blocks_heterogeneous.rs @@ -0,0 +1,34 @@ +// rustfmt-edition: 2018 + +fn main() -> Result<(), !> { + let _x = try bikeshed Option<_> { + 4 + }; + + try bikeshed Result<_, _> {} +} + +fn baz() -> Option { + if (1 == 1) { + return try bikeshed Option { + 5 + }; + } + + // test + let x = try bikeshed Option<()> { + // try blocks are great + }; + + let y = try bikeshed Option { + 6 + }; // comment + + let x = try bikeshed Option { baz()?; baz()?; baz()?; 7 }; + + let x = try bikeshed Foo { 1 + 1 + 1 }; + + let x = try bikeshed Foo {}; + + return None; +} diff --git a/src/tools/rustfmt/tests/target/try_blocks_heterogeneous.rs b/src/tools/rustfmt/tests/target/try_blocks_heterogeneous.rs new file mode 100644 index 0000000000000..6f910ed5d0519 --- /dev/null +++ b/src/tools/rustfmt/tests/target/try_blocks_heterogeneous.rs @@ -0,0 +1,36 @@ +// rustfmt-edition: 2018 + +fn main() -> Result<(), !> { + let _x = try bikeshed Option<_> { 4 }; + + try bikeshed Result<_, _> {} +} + +fn baz() -> Option { + if (1 == 1) { + return try bikeshed Option { 5 }; + } + + // test + let x = try bikeshed Option<()> { + // try blocks are great + }; + + let y = try bikeshed Option { 6 }; // comment + + let x = try bikeshed Option { + baz()?; + baz()?; + baz()?; + 7 + }; + + let x = try bikeshed Foo { + 1 + 1 + 1 + }; + + let x = + try bikeshed Foo {}; + + return None; +} From d5c6866dbadbf4c410faf6ab8b01c0f88631e171 Mon Sep 17 00:00:00 2001 From: ia0 Date: Sat, 7 Feb 2026 22:06:55 +0100 Subject: [PATCH 04/11] improve tests --- src/tools/rustfmt/tests/source/try_block.rs | 1 + src/tools/rustfmt/tests/source/try_blocks_heterogeneous.rs | 5 +++++ src/tools/rustfmt/tests/target/try_block.rs | 1 + src/tools/rustfmt/tests/target/try_blocks_heterogeneous.rs | 5 +++++ 4 files changed, 12 insertions(+) diff --git a/src/tools/rustfmt/tests/source/try_block.rs b/src/tools/rustfmt/tests/source/try_block.rs index 2e8d61f7e66a5..e324a13317584 100644 --- a/src/tools/rustfmt/tests/source/try_block.rs +++ b/src/tools/rustfmt/tests/source/try_block.rs @@ -1,4 +1,5 @@ // rustfmt-edition: 2018 +#![feature(try_blocks)] fn main() -> Result<(), !> { let _x: Option<_> = try { diff --git a/src/tools/rustfmt/tests/source/try_blocks_heterogeneous.rs b/src/tools/rustfmt/tests/source/try_blocks_heterogeneous.rs index bae0060374d88..7a1135cfbc764 100644 --- a/src/tools/rustfmt/tests/source/try_blocks_heterogeneous.rs +++ b/src/tools/rustfmt/tests/source/try_blocks_heterogeneous.rs @@ -1,4 +1,5 @@ // rustfmt-edition: 2018 +#![feature(try_blocks_heterogeneous)] fn main() -> Result<(), !> { let _x = try bikeshed Option<_> { @@ -24,6 +25,10 @@ fn baz() -> Option { 6 }; // comment + let x = try /* Invisible comment */ bikeshed Option<()> {}; + let x = try bikeshed /* Invisible comment */ Option<()> {}; + let x = try bikeshed Option<()> /* Invisible comment */ {}; + let x = try bikeshed Option { baz()?; baz()?; baz()?; 7 }; let x = try bikeshed Foo { 1 + 1 + 1 }; diff --git a/src/tools/rustfmt/tests/target/try_block.rs b/src/tools/rustfmt/tests/target/try_block.rs index 19a3f3e148769..61da123b735d8 100644 --- a/src/tools/rustfmt/tests/target/try_block.rs +++ b/src/tools/rustfmt/tests/target/try_block.rs @@ -1,4 +1,5 @@ // rustfmt-edition: 2018 +#![feature(try_blocks)] fn main() -> Result<(), !> { let _x: Option<_> = try { 4 }; diff --git a/src/tools/rustfmt/tests/target/try_blocks_heterogeneous.rs b/src/tools/rustfmt/tests/target/try_blocks_heterogeneous.rs index 6f910ed5d0519..018d53ed35e41 100644 --- a/src/tools/rustfmt/tests/target/try_blocks_heterogeneous.rs +++ b/src/tools/rustfmt/tests/target/try_blocks_heterogeneous.rs @@ -1,4 +1,5 @@ // rustfmt-edition: 2018 +#![feature(try_blocks_heterogeneous)] fn main() -> Result<(), !> { let _x = try bikeshed Option<_> { 4 }; @@ -18,6 +19,10 @@ fn baz() -> Option { let y = try bikeshed Option { 6 }; // comment + let x = try /* Invisible comment */ bikeshed Option<()> {}; + let x = try bikeshed /* Invisible comment */ Option<()> {}; + let x = try bikeshed Option<()> /* Invisible comment */ {}; + let x = try bikeshed Option { baz()?; baz()?; From 90fd76845cc73288f680f0d14d55f511bfe41fac Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 4 Jan 2026 16:52:51 +1100 Subject: [PATCH 05/11] Make it clearer that `check_pat_lit` only handles literal patterns --- compiler/rustc_hir_typeck/src/pat.rs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index f054145dc7e9a..13f87c0923526 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -3,6 +3,7 @@ use std::collections::hash_map::Entry::{Occupied, Vacant}; use rustc_abi::FieldIdx; use rustc_ast as ast; +use rustc_data_structures::assert_matches; use rustc_data_structures::fx::FxHashMap; use rustc_errors::codes::*; use rustc_errors::{ @@ -24,7 +25,6 @@ use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS; use rustc_session::parse::feature_err; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::edition::Edition; -use rustc_span::source_map::Spanned; use rustc_span::{BytePos, DUMMY_SP, Ident, Span, kw, sym}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode}; @@ -611,7 +611,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.write_ty(*hir_id, ty); ty } - PatKind::Expr(lt) => self.check_pat_lit(pat.span, lt, expected, &pat_info.top_info), + PatKind::Expr(expr @ PatExpr { kind: PatExprKind::Lit { lit, .. }, .. }) => { + self.check_pat_lit(pat.span, expr, &lit.node, expected, &pat_info.top_info) + } PatKind::Range(lhs, rhs, _) => { self.check_pat_range(pat.span, lhs, rhs, expected, &pat_info.top_info) } @@ -938,23 +940,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn check_pat_lit( &self, span: Span, - lt: &hir::PatExpr<'tcx>, + expr: &hir::PatExpr<'tcx>, + lit_kind: &ast::LitKind, expected: Ty<'tcx>, ti: &TopInfo<'tcx>, ) -> Ty<'tcx> { + assert_matches!(expr.kind, hir::PatExprKind::Lit { .. }); + // We've already computed the type above (when checking for a non-ref pat), // so avoid computing it again. - let ty = self.node_ty(lt.hir_id); + let ty = self.node_ty(expr.hir_id); // Byte string patterns behave the same way as array patterns // They can denote both statically and dynamically-sized byte arrays. // Additionally, when `deref_patterns` is enabled, byte string literal patterns may have // types `[u8]` or `[u8; N]`, in order to type, e.g., `deref!(b"..."): Vec`. let mut pat_ty = ty; - if let hir::PatExprKind::Lit { - lit: Spanned { node: ast::LitKind::ByteStr(..), .. }, .. - } = lt.kind - { + if matches!(lit_kind, ast::LitKind::ByteStr(..)) { let tcx = self.tcx; let expected = self.structurally_resolve_type(span, expected); match *expected.kind() { @@ -962,7 +964,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::Ref(_, inner_ty, _) if self.try_structurally_resolve_type(span, inner_ty).is_slice() => { - trace!(?lt.hir_id.local_id, "polymorphic byte string lit"); + trace!(?expr.hir_id.local_id, "polymorphic byte string lit"); pat_ty = Ty::new_imm_ref( tcx, tcx.lifetimes.re_static, @@ -988,9 +990,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // When `deref_patterns` is enabled, in order to allow `deref!("..."): String`, we allow // string literal patterns to have type `str`. This is accounted for when lowering to MIR. if self.tcx.features().deref_patterns() - && let hir::PatExprKind::Lit { - lit: Spanned { node: ast::LitKind::Str(..), .. }, .. - } = lt.kind + && matches!(lit_kind, ast::LitKind::Str(..)) && self.try_structurally_resolve_type(span, expected).is_str() { pat_ty = self.tcx.types.str_; From 91d47a5c0d82cce04c1e4aef2eacad4f8c9b7e8b Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 8 Feb 2026 13:40:20 +1100 Subject: [PATCH 06/11] Don't import `TyCtxt` from `crate::ty::context` --- .../rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs | 3 +-- compiler/rustc_middle/src/ty/inhabitedness/mod.rs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs b/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs index d03e593e37b91..c935869b504cd 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs @@ -2,8 +2,7 @@ use rustc_macros::HashStable; use smallvec::SmallVec; use tracing::instrument; -use crate::ty::context::TyCtxt; -use crate::ty::{self, DefId, OpaqueTypeKey, Ty, TypingEnv}; +use crate::ty::{self, DefId, OpaqueTypeKey, Ty, TyCtxt, TypingEnv}; /// Represents whether some type is inhabited in a given context. /// Examples of uninhabited types are `!`, `enum Void {}`, or a struct diff --git a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs index 7eb74b52b44c6..5c4c1733be29e 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs @@ -47,8 +47,7 @@ use rustc_type_ir::TyKind::*; use tracing::instrument; use crate::query::Providers; -use crate::ty::context::TyCtxt; -use crate::ty::{self, DefId, Ty, TypeVisitableExt, VariantDef, Visibility}; +use crate::ty::{self, DefId, Ty, TyCtxt, TypeVisitableExt, VariantDef, Visibility}; pub mod inhabited_predicate; From 4234d2dd72b38069981a6ba0c4c6befb22d3276b Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 8 Feb 2026 13:40:20 +1100 Subject: [PATCH 07/11] Move `impl Interner for TyCtxt` to its own submodule --- compiler/rustc_middle/src/ty/context.rs | 808 +----------------- .../src/ty/context/impl_interner.rs | 804 +++++++++++++++++ 2 files changed, 815 insertions(+), 797 deletions(-) create mode 100644 compiler/rustc_middle/src/ty/context/impl_interner.rs diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 1bb83530487df..fbb959ce710de 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -2,6 +2,7 @@ #![allow(rustc::usage_of_ty_tykind)] +mod impl_interner; pub mod tls; use std::borrow::{Borrow, Cow}; @@ -16,6 +17,7 @@ use std::{fmt, iter, mem}; use rustc_abi::{ExternAbi, FieldIdx, Layout, LayoutData, TargetDataLayout, VariantIdx}; use rustc_ast as ast; +use rustc_data_structures::defer; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::intern::Interned; @@ -27,12 +29,9 @@ use rustc_data_structures::steal::Steal; use rustc_data_structures::sync::{ self, DynSend, DynSync, FreezeReadGuard, Lock, RwLock, WorkerLocal, }; -use rustc_data_structures::{debug_assert_matches, defer}; -use rustc_errors::{ - Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, LintDiagnostic, MultiSpan, -}; +use rustc_errors::{Applicability, Diag, DiagCtxtHandle, LintDiagnostic, MultiSpan}; use rustc_hir::attrs::AttributeKind; -use rustc_hir::def::{CtorKind, CtorOf, DefKind}; +use rustc_hir::def::DefKind; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::definitions::{DefPathData, Definitions, DisambiguatorState}; use rustc_hir::intravisit::VisitorExt; @@ -50,16 +49,13 @@ use rustc_session::lint::Lint; use rustc_span::def_id::{CRATE_DEF_ID, DefPathHash, StableCrateId}; use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw}; use rustc_type_ir::TyKind::*; -use rustc_type_ir::lang_items::{SolverAdtLangItem, SolverLangItem, SolverTraitLangItem}; pub use rustc_type_ir::lift::Lift; -use rustc_type_ir::{ - CollectAndApply, Interner, TypeFlags, TypeFoldable, WithCachedTypeInfo, elaborate, search_graph, -}; +use rustc_type_ir::{CollectAndApply, TypeFlags, WithCachedTypeInfo, elaborate, search_graph}; use tracing::{debug, instrument}; use crate::arena::Arena; use crate::dep_graph::{DepGraph, DepKindVTable}; -use crate::infer::canonical::{CanonicalParamEnvCache, CanonicalVarKind, CanonicalVarKinds}; +use crate::infer::canonical::{CanonicalParamEnvCache, CanonicalVarKind}; use crate::lint::lint_level; use crate::metadata::ModChild; use crate::middle::codegen_fn_attrs::{CodegenFnAttrs, TargetFeature}; @@ -70,798 +66,16 @@ use crate::query::plumbing::QuerySystem; use crate::query::{IntoQueryParam, LocalCrate, Providers, TyCtxtAt}; use crate::thir::Thir; use crate::traits; -use crate::traits::cache::WithDepNode; -use crate::traits::solve::{ - self, CanonicalInput, ExternalConstraints, ExternalConstraintsData, PredefinedOpaques, - QueryResult, inspect, -}; +use crate::traits::solve::{ExternalConstraints, ExternalConstraintsData, PredefinedOpaques}; use crate::ty::predicate::ExistentialPredicateStableCmpExt as _; use crate::ty::{ self, AdtDef, AdtDefData, AdtKind, Binder, Clause, Clauses, Const, GenericArg, GenericArgs, - GenericArgsRef, GenericParamDefKind, List, ListWithCachedTypeInfo, ParamConst, ParamTy, - Pattern, PatternKind, PolyExistentialPredicate, PolyFnSig, Predicate, PredicateKind, - PredicatePolarity, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyVid, - ValTree, ValTreeKind, Visibility, + GenericArgsRef, GenericParamDefKind, List, ListWithCachedTypeInfo, ParamConst, Pattern, + PatternKind, PolyExistentialPredicate, PolyFnSig, Predicate, PredicateKind, PredicatePolarity, + Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyVid, ValTree, ValTreeKind, + Visibility, }; -#[allow(rustc::usage_of_ty_tykind)] -impl<'tcx> Interner for TyCtxt<'tcx> { - fn next_trait_solver_globally(self) -> bool { - self.next_trait_solver_globally() - } - - type DefId = DefId; - type LocalDefId = LocalDefId; - type TraitId = DefId; - type ForeignId = DefId; - type FunctionId = DefId; - type ClosureId = DefId; - type CoroutineClosureId = DefId; - type CoroutineId = DefId; - type AdtId = DefId; - type ImplId = DefId; - type UnevaluatedConstId = DefId; - type Span = Span; - - type GenericArgs = ty::GenericArgsRef<'tcx>; - - type GenericArgsSlice = &'tcx [ty::GenericArg<'tcx>]; - type GenericArg = ty::GenericArg<'tcx>; - type Term = ty::Term<'tcx>; - type BoundVarKinds = &'tcx List>; - - type PredefinedOpaques = solve::PredefinedOpaques<'tcx>; - - fn mk_predefined_opaques_in_body( - self, - data: &[(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)], - ) -> Self::PredefinedOpaques { - self.mk_predefined_opaques_in_body(data) - } - type LocalDefIds = &'tcx ty::List; - type CanonicalVarKinds = CanonicalVarKinds<'tcx>; - fn mk_canonical_var_kinds( - self, - kinds: &[ty::CanonicalVarKind], - ) -> Self::CanonicalVarKinds { - self.mk_canonical_var_kinds(kinds) - } - - type ExternalConstraints = ExternalConstraints<'tcx>; - fn mk_external_constraints( - self, - data: ExternalConstraintsData, - ) -> ExternalConstraints<'tcx> { - self.mk_external_constraints(data) - } - type DepNodeIndex = DepNodeIndex; - fn with_cached_task(self, task: impl FnOnce() -> T) -> (T, DepNodeIndex) { - self.dep_graph.with_anon_task(self, crate::dep_graph::dep_kinds::TraitSelect, task) - } - type Ty = Ty<'tcx>; - type Tys = &'tcx List>; - - type FnInputTys = &'tcx [Ty<'tcx>]; - type ParamTy = ParamTy; - type Symbol = Symbol; - - type ErrorGuaranteed = ErrorGuaranteed; - type BoundExistentialPredicates = &'tcx List>; - - type AllocId = crate::mir::interpret::AllocId; - type Pat = Pattern<'tcx>; - type PatList = &'tcx List>; - type Safety = hir::Safety; - type Abi = ExternAbi; - type Const = ty::Const<'tcx>; - - type ParamConst = ty::ParamConst; - type ValueConst = ty::Value<'tcx>; - type ExprConst = ty::Expr<'tcx>; - type ValTree = ty::ValTree<'tcx>; - type ScalarInt = ty::ScalarInt; - - type Region = Region<'tcx>; - type EarlyParamRegion = ty::EarlyParamRegion; - type LateParamRegion = ty::LateParamRegion; - - type RegionAssumptions = &'tcx ty::List>; - - type ParamEnv = ty::ParamEnv<'tcx>; - type Predicate = Predicate<'tcx>; - - type Clause = Clause<'tcx>; - type Clauses = ty::Clauses<'tcx>; - - type Tracked = WithDepNode; - fn mk_tracked( - self, - data: T, - dep_node: DepNodeIndex, - ) -> Self::Tracked { - WithDepNode::new(dep_node, data) - } - fn get_tracked(self, tracked: &Self::Tracked) -> T { - tracked.get(self) - } - - fn with_global_cache(self, f: impl FnOnce(&mut search_graph::GlobalCache) -> R) -> R { - f(&mut *self.new_solver_evaluation_cache.lock()) - } - - fn canonical_param_env_cache_get_or_insert( - self, - param_env: ty::ParamEnv<'tcx>, - f: impl FnOnce() -> ty::CanonicalParamEnvCacheEntry, - from_entry: impl FnOnce(&ty::CanonicalParamEnvCacheEntry) -> R, - ) -> R { - let mut cache = self.new_solver_canonical_param_env_cache.lock(); - let entry = cache.entry(param_env).or_insert_with(f); - from_entry(entry) - } - - fn assert_evaluation_is_concurrent(&self) { - // Turns out, the assumption for this function isn't perfect. - // See trait-system-refactor-initiative#234. - } - - fn expand_abstract_consts>>(self, t: T) -> T { - self.expand_abstract_consts(t) - } - - type GenericsOf = &'tcx ty::Generics; - - fn generics_of(self, def_id: DefId) -> &'tcx ty::Generics { - self.generics_of(def_id) - } - - type VariancesOf = &'tcx [ty::Variance]; - - fn variances_of(self, def_id: DefId) -> Self::VariancesOf { - self.variances_of(def_id) - } - - fn opt_alias_variances( - self, - kind: impl Into, - def_id: DefId, - ) -> Option<&'tcx [ty::Variance]> { - self.opt_alias_variances(kind, def_id) - } - - fn type_of(self, def_id: DefId) -> ty::EarlyBinder<'tcx, Ty<'tcx>> { - self.type_of(def_id) - } - fn type_of_opaque_hir_typeck(self, def_id: LocalDefId) -> ty::EarlyBinder<'tcx, Ty<'tcx>> { - self.type_of_opaque_hir_typeck(def_id) - } - fn const_of_item(self, def_id: DefId) -> ty::EarlyBinder<'tcx, Const<'tcx>> { - self.const_of_item(def_id) - } - fn anon_const_kind(self, def_id: DefId) -> ty::AnonConstKind { - self.anon_const_kind(def_id) - } - - type AdtDef = ty::AdtDef<'tcx>; - fn adt_def(self, adt_def_id: DefId) -> Self::AdtDef { - self.adt_def(adt_def_id) - } - - fn alias_ty_kind(self, alias: ty::AliasTy<'tcx>) -> ty::AliasTyKind { - match self.def_kind(alias.def_id) { - DefKind::AssocTy => { - if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(alias.def_id)) - { - ty::Inherent - } else { - ty::Projection - } - } - DefKind::OpaqueTy => ty::Opaque, - DefKind::TyAlias => ty::Free, - kind => bug!("unexpected DefKind in AliasTy: {kind:?}"), - } - } - - fn alias_term_kind(self, alias: ty::AliasTerm<'tcx>) -> ty::AliasTermKind { - match self.def_kind(alias.def_id) { - DefKind::AssocTy => { - if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(alias.def_id)) - { - ty::AliasTermKind::InherentTy - } else { - ty::AliasTermKind::ProjectionTy - } - } - DefKind::AssocConst => { - if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(alias.def_id)) - { - ty::AliasTermKind::InherentConst - } else { - ty::AliasTermKind::ProjectionConst - } - } - DefKind::OpaqueTy => ty::AliasTermKind::OpaqueTy, - DefKind::TyAlias => ty::AliasTermKind::FreeTy, - DefKind::Const => ty::AliasTermKind::FreeConst, - DefKind::AnonConst | DefKind::Ctor(_, CtorKind::Const) => { - ty::AliasTermKind::UnevaluatedConst - } - kind => bug!("unexpected DefKind in AliasTy: {kind:?}"), - } - } - - fn trait_ref_and_own_args_for_alias( - self, - def_id: DefId, - args: ty::GenericArgsRef<'tcx>, - ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { - debug_assert_matches!(self.def_kind(def_id), DefKind::AssocTy | DefKind::AssocConst); - let trait_def_id = self.parent(def_id); - debug_assert_matches!(self.def_kind(trait_def_id), DefKind::Trait); - let trait_ref = ty::TraitRef::from_assoc(self, trait_def_id, args); - (trait_ref, &args[trait_ref.args.len()..]) - } - - fn mk_args(self, args: &[Self::GenericArg]) -> ty::GenericArgsRef<'tcx> { - self.mk_args(args) - } - - fn mk_args_from_iter(self, args: I) -> T::Output - where - I: Iterator, - T: CollectAndApply>, - { - self.mk_args_from_iter(args) - } - - fn check_args_compatible(self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> bool { - self.check_args_compatible(def_id, args) - } - - fn debug_assert_args_compatible(self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) { - self.debug_assert_args_compatible(def_id, args); - } - - /// Assert that the args from an `ExistentialTraitRef` or `ExistentialProjection` - /// are compatible with the `DefId`. Since we're missing a `Self` type, stick on - /// a dummy self type and forward to `debug_assert_args_compatible`. - fn debug_assert_existential_args_compatible( - self, - def_id: Self::DefId, - args: Self::GenericArgs, - ) { - // FIXME: We could perhaps add a `skip: usize` to `debug_assert_args_compatible` - // to avoid needing to reintern the set of args... - if cfg!(debug_assertions) { - self.debug_assert_args_compatible( - def_id, - self.mk_args_from_iter( - [self.types.trait_object_dummy_self.into()].into_iter().chain(args.iter()), - ), - ); - } - } - - fn mk_type_list_from_iter(self, args: I) -> T::Output - where - I: Iterator, - T: CollectAndApply, &'tcx List>>, - { - self.mk_type_list_from_iter(args) - } - - fn parent(self, def_id: DefId) -> DefId { - self.parent(def_id) - } - - fn recursion_limit(self) -> usize { - self.recursion_limit().0 - } - - type Features = &'tcx rustc_feature::Features; - - fn features(self) -> Self::Features { - self.features() - } - - fn coroutine_hidden_types( - self, - def_id: DefId, - ) -> ty::EarlyBinder<'tcx, ty::Binder<'tcx, ty::CoroutineWitnessTypes>>> { - self.coroutine_hidden_types(def_id) - } - - fn fn_sig(self, def_id: DefId) -> ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>> { - self.fn_sig(def_id) - } - - fn coroutine_movability(self, def_id: DefId) -> rustc_ast::Movability { - self.coroutine_movability(def_id) - } - - fn coroutine_for_closure(self, def_id: DefId) -> DefId { - self.coroutine_for_closure(def_id) - } - - fn generics_require_sized_self(self, def_id: DefId) -> bool { - self.generics_require_sized_self(def_id) - } - - fn item_bounds( - self, - def_id: DefId, - ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { - self.item_bounds(def_id).map_bound(IntoIterator::into_iter) - } - - fn item_self_bounds( - self, - def_id: DefId, - ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { - self.item_self_bounds(def_id).map_bound(IntoIterator::into_iter) - } - - fn item_non_self_bounds( - self, - def_id: DefId, - ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { - self.item_non_self_bounds(def_id).map_bound(IntoIterator::into_iter) - } - - fn predicates_of( - self, - def_id: DefId, - ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { - ty::EarlyBinder::bind( - self.predicates_of(def_id).instantiate_identity(self).predicates.into_iter(), - ) - } - - fn own_predicates_of( - self, - def_id: DefId, - ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { - ty::EarlyBinder::bind( - self.predicates_of(def_id).instantiate_own_identity().map(|(clause, _)| clause), - ) - } - - fn explicit_super_predicates_of( - self, - def_id: DefId, - ) -> ty::EarlyBinder<'tcx, impl IntoIterator, Span)>> { - self.explicit_super_predicates_of(def_id).map_bound(|preds| preds.into_iter().copied()) - } - - fn explicit_implied_predicates_of( - self, - def_id: DefId, - ) -> ty::EarlyBinder<'tcx, impl IntoIterator, Span)>> { - self.explicit_implied_predicates_of(def_id).map_bound(|preds| preds.into_iter().copied()) - } - - fn impl_super_outlives( - self, - impl_def_id: DefId, - ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { - self.impl_super_outlives(impl_def_id) - } - - fn impl_is_const(self, def_id: DefId) -> bool { - debug_assert_matches!(self.def_kind(def_id), DefKind::Impl { of_trait: true }); - self.is_conditionally_const(def_id) - } - - fn fn_is_const(self, def_id: DefId) -> bool { - debug_assert_matches!( - self.def_kind(def_id), - DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) - ); - self.is_conditionally_const(def_id) - } - - fn alias_has_const_conditions(self, def_id: DefId) -> bool { - debug_assert_matches!(self.def_kind(def_id), DefKind::AssocTy | DefKind::OpaqueTy); - self.is_conditionally_const(def_id) - } - - fn const_conditions( - self, - def_id: DefId, - ) -> ty::EarlyBinder<'tcx, impl IntoIterator>>> { - ty::EarlyBinder::bind( - self.const_conditions(def_id).instantiate_identity(self).into_iter().map(|(c, _)| c), - ) - } - - fn explicit_implied_const_bounds( - self, - def_id: DefId, - ) -> ty::EarlyBinder<'tcx, impl IntoIterator>>> { - ty::EarlyBinder::bind( - self.explicit_implied_const_bounds(def_id).iter_identity_copied().map(|(c, _)| c), - ) - } - - fn impl_self_is_guaranteed_unsized(self, impl_def_id: DefId) -> bool { - self.impl_self_is_guaranteed_unsized(impl_def_id) - } - - fn has_target_features(self, def_id: DefId) -> bool { - !self.codegen_fn_attrs(def_id).target_features.is_empty() - } - - fn require_lang_item(self, lang_item: SolverLangItem) -> DefId { - self.require_lang_item(solver_lang_item_to_lang_item(lang_item), DUMMY_SP) - } - - fn require_trait_lang_item(self, lang_item: SolverTraitLangItem) -> DefId { - self.require_lang_item(solver_trait_lang_item_to_lang_item(lang_item), DUMMY_SP) - } - - fn require_adt_lang_item(self, lang_item: SolverAdtLangItem) -> DefId { - self.require_lang_item(solver_adt_lang_item_to_lang_item(lang_item), DUMMY_SP) - } - - fn is_lang_item(self, def_id: DefId, lang_item: SolverLangItem) -> bool { - self.is_lang_item(def_id, solver_lang_item_to_lang_item(lang_item)) - } - - fn is_trait_lang_item(self, def_id: DefId, lang_item: SolverTraitLangItem) -> bool { - self.is_lang_item(def_id, solver_trait_lang_item_to_lang_item(lang_item)) - } - - fn is_adt_lang_item(self, def_id: DefId, lang_item: SolverAdtLangItem) -> bool { - self.is_lang_item(def_id, solver_adt_lang_item_to_lang_item(lang_item)) - } - - fn is_default_trait(self, def_id: DefId) -> bool { - self.is_default_trait(def_id) - } - - fn is_sizedness_trait(self, def_id: DefId) -> bool { - self.is_sizedness_trait(def_id) - } - - fn as_lang_item(self, def_id: DefId) -> Option { - lang_item_to_solver_lang_item(self.lang_items().from_def_id(def_id)?) - } - - fn as_trait_lang_item(self, def_id: DefId) -> Option { - lang_item_to_solver_trait_lang_item(self.lang_items().from_def_id(def_id)?) - } - - fn as_adt_lang_item(self, def_id: DefId) -> Option { - lang_item_to_solver_adt_lang_item(self.lang_items().from_def_id(def_id)?) - } - - fn associated_type_def_ids(self, def_id: DefId) -> impl IntoIterator { - self.associated_items(def_id) - .in_definition_order() - .filter(|assoc_item| assoc_item.is_type()) - .map(|assoc_item| assoc_item.def_id) - } - - // This implementation is a bit different from `TyCtxt::for_each_relevant_impl`, - // since we want to skip over blanket impls for non-rigid aliases, and also we - // only want to consider types that *actually* unify with float/int vars. - fn for_each_relevant_impl( - self, - trait_def_id: DefId, - self_ty: Ty<'tcx>, - mut f: impl FnMut(DefId), - ) { - let tcx = self; - let trait_impls = tcx.trait_impls_of(trait_def_id); - let mut consider_impls_for_simplified_type = |simp| { - if let Some(impls_for_type) = trait_impls.non_blanket_impls().get(&simp) { - for &impl_def_id in impls_for_type { - f(impl_def_id); - } - } - }; - - match self_ty.kind() { - ty::Bool - | ty::Char - | ty::Int(_) - | ty::Uint(_) - | ty::Float(_) - | ty::Adt(_, _) - | ty::Foreign(_) - | ty::Str - | ty::Array(_, _) - | ty::Pat(_, _) - | ty::Slice(_) - | ty::RawPtr(_, _) - | ty::Ref(_, _, _) - | ty::FnDef(_, _) - | ty::FnPtr(..) - | ty::Dynamic(_, _) - | ty::Closure(..) - | ty::CoroutineClosure(..) - | ty::Coroutine(_, _) - | ty::Never - | ty::Tuple(_) - | ty::UnsafeBinder(_) => { - if let Some(simp) = ty::fast_reject::simplify_type( - tcx, - self_ty, - ty::fast_reject::TreatParams::AsRigid, - ) { - consider_impls_for_simplified_type(simp); - } - } - - // HACK: For integer and float variables we have to manually look at all impls - // which have some integer or float as a self type. - ty::Infer(ty::IntVar(_)) => { - use ty::IntTy::*; - use ty::UintTy::*; - // This causes a compiler error if any new integer kinds are added. - let (I8 | I16 | I32 | I64 | I128 | Isize): ty::IntTy; - let (U8 | U16 | U32 | U64 | U128 | Usize): ty::UintTy; - let possible_integers = [ - // signed integers - ty::SimplifiedType::Int(I8), - ty::SimplifiedType::Int(I16), - ty::SimplifiedType::Int(I32), - ty::SimplifiedType::Int(I64), - ty::SimplifiedType::Int(I128), - ty::SimplifiedType::Int(Isize), - // unsigned integers - ty::SimplifiedType::Uint(U8), - ty::SimplifiedType::Uint(U16), - ty::SimplifiedType::Uint(U32), - ty::SimplifiedType::Uint(U64), - ty::SimplifiedType::Uint(U128), - ty::SimplifiedType::Uint(Usize), - ]; - for simp in possible_integers { - consider_impls_for_simplified_type(simp); - } - } - - ty::Infer(ty::FloatVar(_)) => { - // This causes a compiler error if any new float kinds are added. - let (ty::FloatTy::F16 | ty::FloatTy::F32 | ty::FloatTy::F64 | ty::FloatTy::F128); - let possible_floats = [ - ty::SimplifiedType::Float(ty::FloatTy::F16), - ty::SimplifiedType::Float(ty::FloatTy::F32), - ty::SimplifiedType::Float(ty::FloatTy::F64), - ty::SimplifiedType::Float(ty::FloatTy::F128), - ]; - - for simp in possible_floats { - consider_impls_for_simplified_type(simp); - } - } - - // The only traits applying to aliases and placeholders are blanket impls. - // - // Impls which apply to an alias after normalization are handled by - // `assemble_candidates_after_normalizing_self_ty`. - ty::Alias(_, _) | ty::Placeholder(..) | ty::Error(_) => (), - - // FIXME: These should ideally not exist as a self type. It would be nice for - // the builtin auto trait impls of coroutines to instead directly recurse - // into the witness. - ty::CoroutineWitness(..) => (), - - // These variants should not exist as a self type. - ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) - | ty::Param(_) - | ty::Bound(_, _) => bug!("unexpected self type: {self_ty}"), - } - - #[allow(rustc::usage_of_type_ir_traits)] - self.for_each_blanket_impl(trait_def_id, f) - } - fn for_each_blanket_impl(self, trait_def_id: DefId, mut f: impl FnMut(DefId)) { - let trait_impls = self.trait_impls_of(trait_def_id); - for &impl_def_id in trait_impls.blanket_impls() { - f(impl_def_id); - } - } - - fn has_item_definition(self, def_id: DefId) -> bool { - self.defaultness(def_id).has_value() - } - - fn impl_specializes(self, impl_def_id: Self::DefId, victim_def_id: Self::DefId) -> bool { - self.specializes((impl_def_id, victim_def_id)) - } - - fn impl_is_default(self, impl_def_id: DefId) -> bool { - self.defaultness(impl_def_id).is_default() - } - - fn impl_trait_ref(self, impl_def_id: DefId) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> { - self.impl_trait_ref(impl_def_id) - } - - fn impl_polarity(self, impl_def_id: DefId) -> ty::ImplPolarity { - self.impl_polarity(impl_def_id) - } - - fn trait_is_auto(self, trait_def_id: DefId) -> bool { - self.trait_is_auto(trait_def_id) - } - - fn trait_is_coinductive(self, trait_def_id: DefId) -> bool { - self.trait_is_coinductive(trait_def_id) - } - - fn trait_is_alias(self, trait_def_id: DefId) -> bool { - self.trait_is_alias(trait_def_id) - } - - fn trait_is_dyn_compatible(self, trait_def_id: DefId) -> bool { - self.is_dyn_compatible(trait_def_id) - } - - fn trait_is_fundamental(self, def_id: DefId) -> bool { - self.trait_def(def_id).is_fundamental - } - - fn trait_is_unsafe(self, trait_def_id: Self::DefId) -> bool { - self.trait_def(trait_def_id).safety.is_unsafe() - } - - fn is_impl_trait_in_trait(self, def_id: DefId) -> bool { - self.is_impl_trait_in_trait(def_id) - } - - fn delay_bug(self, msg: impl ToString) -> ErrorGuaranteed { - self.dcx().span_delayed_bug(DUMMY_SP, msg.to_string()) - } - - fn is_general_coroutine(self, coroutine_def_id: DefId) -> bool { - self.is_general_coroutine(coroutine_def_id) - } - - fn coroutine_is_async(self, coroutine_def_id: DefId) -> bool { - self.coroutine_is_async(coroutine_def_id) - } - - fn coroutine_is_gen(self, coroutine_def_id: DefId) -> bool { - self.coroutine_is_gen(coroutine_def_id) - } - - fn coroutine_is_async_gen(self, coroutine_def_id: DefId) -> bool { - self.coroutine_is_async_gen(coroutine_def_id) - } - - type UnsizingParams = &'tcx rustc_index::bit_set::DenseBitSet; - fn unsizing_params_for_adt(self, adt_def_id: DefId) -> Self::UnsizingParams { - self.unsizing_params_for_adt(adt_def_id) - } - - fn anonymize_bound_vars>>( - self, - binder: ty::Binder<'tcx, T>, - ) -> ty::Binder<'tcx, T> { - self.anonymize_bound_vars(binder) - } - - fn opaque_types_defined_by(self, defining_anchor: LocalDefId) -> Self::LocalDefIds { - self.opaque_types_defined_by(defining_anchor) - } - - fn opaque_types_and_coroutines_defined_by( - self, - defining_anchor: Self::LocalDefId, - ) -> Self::LocalDefIds { - let coroutines_defined_by = self - .nested_bodies_within(defining_anchor) - .iter() - .filter(|def_id| self.is_coroutine(def_id.to_def_id())); - self.mk_local_def_ids_from_iter( - self.opaque_types_defined_by(defining_anchor).iter().chain(coroutines_defined_by), - ) - } - - type Probe = &'tcx inspect::Probe>; - fn mk_probe(self, probe: inspect::Probe) -> &'tcx inspect::Probe> { - self.arena.alloc(probe) - } - fn evaluate_root_goal_for_proof_tree_raw( - self, - canonical_goal: CanonicalInput<'tcx>, - ) -> (QueryResult<'tcx>, &'tcx inspect::Probe>) { - self.evaluate_root_goal_for_proof_tree_raw(canonical_goal) - } - - fn item_name(self, id: DefId) -> Symbol { - let id = id.into_query_param(); - self.opt_item_name(id).unwrap_or_else(|| { - bug!("item_name: no name for {:?}", self.def_path(id)); - }) - } -} - -macro_rules! bidirectional_lang_item_map { - ( - $solver_ty:ident, $to_solver:ident, $from_solver:ident; - $($name:ident),+ $(,)? - ) => { - fn $from_solver(lang_item: $solver_ty) -> LangItem { - match lang_item { - $($solver_ty::$name => LangItem::$name,)+ - } - } - - fn $to_solver(lang_item: LangItem) -> Option<$solver_ty> { - Some(match lang_item { - $(LangItem::$name => $solver_ty::$name,)+ - _ => return None, - }) - } - } -} - -bidirectional_lang_item_map! { - SolverLangItem, lang_item_to_solver_lang_item, solver_lang_item_to_lang_item; - -// tidy-alphabetical-start - AsyncFnKindUpvars, - AsyncFnOnceOutput, - CallOnceFuture, - CallRefFuture, - CoroutineReturn, - CoroutineYield, - DynMetadata, - FutureOutput, - Metadata, -// tidy-alphabetical-end -} - -bidirectional_lang_item_map! { - SolverAdtLangItem, lang_item_to_solver_adt_lang_item, solver_adt_lang_item_to_lang_item; - -// tidy-alphabetical-start - Option, - Poll, -// tidy-alphabetical-end -} - -bidirectional_lang_item_map! { - SolverTraitLangItem, lang_item_to_solver_trait_lang_item, solver_trait_lang_item_to_lang_item; - -// tidy-alphabetical-start - AsyncFn, - AsyncFnKindHelper, - AsyncFnMut, - AsyncFnOnce, - AsyncFnOnceOutput, - AsyncIterator, - BikeshedGuaranteedNoDrop, - Clone, - Copy, - Coroutine, - Destruct, - DiscriminantKind, - Drop, - Fn, - FnMut, - FnOnce, - FnPtrTrait, - FusedIterator, - Future, - Iterator, - MetaSized, - PointeeSized, - PointeeTrait, - Sized, - TransmuteTrait, - TrivialClone, - Tuple, - Unpin, - Unsize, -// tidy-alphabetical-end -} - impl<'tcx> rustc_type_ir::inherent::DefId> for DefId { fn is_local(self) -> bool { self.is_local() diff --git a/compiler/rustc_middle/src/ty/context/impl_interner.rs b/compiler/rustc_middle/src/ty/context/impl_interner.rs new file mode 100644 index 0000000000000..c449f29634e2c --- /dev/null +++ b/compiler/rustc_middle/src/ty/context/impl_interner.rs @@ -0,0 +1,804 @@ +//! Implementation of [`rustc_type_ir::Interner`] for [`TyCtxt`]. + +use std::fmt; + +use rustc_abi::ExternAbi; +use rustc_data_structures::debug_assert_matches; +use rustc_errors::ErrorGuaranteed; +use rustc_hir::def::{CtorKind, CtorOf, DefKind}; +use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::lang_items::LangItem; +use rustc_hir::{self as hir}; +use rustc_query_system::dep_graph::DepNodeIndex; +use rustc_span::{DUMMY_SP, Span, Symbol}; +use rustc_type_ir::lang_items::{SolverAdtLangItem, SolverLangItem, SolverTraitLangItem}; +use rustc_type_ir::{CollectAndApply, Interner, TypeFoldable, search_graph}; + +use crate::infer::canonical::CanonicalVarKinds; +use crate::query::IntoQueryParam; +use crate::traits::cache::WithDepNode; +use crate::traits::solve::{ + self, CanonicalInput, ExternalConstraints, ExternalConstraintsData, QueryResult, inspect, +}; +use crate::ty::{ + self, Clause, Const, List, ParamTy, Pattern, PolyExistentialPredicate, Predicate, Region, Ty, + TyCtxt, +}; + +#[allow(rustc::usage_of_ty_tykind)] +impl<'tcx> Interner for TyCtxt<'tcx> { + fn next_trait_solver_globally(self) -> bool { + self.next_trait_solver_globally() + } + + type DefId = DefId; + type LocalDefId = LocalDefId; + type TraitId = DefId; + type ForeignId = DefId; + type FunctionId = DefId; + type ClosureId = DefId; + type CoroutineClosureId = DefId; + type CoroutineId = DefId; + type AdtId = DefId; + type ImplId = DefId; + type UnevaluatedConstId = DefId; + type Span = Span; + + type GenericArgs = ty::GenericArgsRef<'tcx>; + + type GenericArgsSlice = &'tcx [ty::GenericArg<'tcx>]; + type GenericArg = ty::GenericArg<'tcx>; + type Term = ty::Term<'tcx>; + type BoundVarKinds = &'tcx List>; + + type PredefinedOpaques = solve::PredefinedOpaques<'tcx>; + + fn mk_predefined_opaques_in_body( + self, + data: &[(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)], + ) -> Self::PredefinedOpaques { + self.mk_predefined_opaques_in_body(data) + } + type LocalDefIds = &'tcx ty::List; + type CanonicalVarKinds = CanonicalVarKinds<'tcx>; + fn mk_canonical_var_kinds( + self, + kinds: &[ty::CanonicalVarKind], + ) -> Self::CanonicalVarKinds { + self.mk_canonical_var_kinds(kinds) + } + + type ExternalConstraints = ExternalConstraints<'tcx>; + fn mk_external_constraints( + self, + data: ExternalConstraintsData, + ) -> ExternalConstraints<'tcx> { + self.mk_external_constraints(data) + } + type DepNodeIndex = DepNodeIndex; + fn with_cached_task(self, task: impl FnOnce() -> T) -> (T, DepNodeIndex) { + self.dep_graph.with_anon_task(self, crate::dep_graph::dep_kinds::TraitSelect, task) + } + type Ty = Ty<'tcx>; + type Tys = &'tcx List>; + + type FnInputTys = &'tcx [Ty<'tcx>]; + type ParamTy = ParamTy; + type Symbol = Symbol; + + type ErrorGuaranteed = ErrorGuaranteed; + type BoundExistentialPredicates = &'tcx List>; + + type AllocId = crate::mir::interpret::AllocId; + type Pat = Pattern<'tcx>; + type PatList = &'tcx List>; + type Safety = hir::Safety; + type Abi = ExternAbi; + type Const = ty::Const<'tcx>; + + type ParamConst = ty::ParamConst; + type ValueConst = ty::Value<'tcx>; + type ExprConst = ty::Expr<'tcx>; + type ValTree = ty::ValTree<'tcx>; + type ScalarInt = ty::ScalarInt; + + type Region = Region<'tcx>; + type EarlyParamRegion = ty::EarlyParamRegion; + type LateParamRegion = ty::LateParamRegion; + + type RegionAssumptions = &'tcx ty::List>; + + type ParamEnv = ty::ParamEnv<'tcx>; + type Predicate = Predicate<'tcx>; + + type Clause = Clause<'tcx>; + type Clauses = ty::Clauses<'tcx>; + + type Tracked = WithDepNode; + fn mk_tracked( + self, + data: T, + dep_node: DepNodeIndex, + ) -> Self::Tracked { + WithDepNode::new(dep_node, data) + } + fn get_tracked(self, tracked: &Self::Tracked) -> T { + tracked.get(self) + } + + fn with_global_cache(self, f: impl FnOnce(&mut search_graph::GlobalCache) -> R) -> R { + f(&mut *self.new_solver_evaluation_cache.lock()) + } + + fn canonical_param_env_cache_get_or_insert( + self, + param_env: ty::ParamEnv<'tcx>, + f: impl FnOnce() -> ty::CanonicalParamEnvCacheEntry, + from_entry: impl FnOnce(&ty::CanonicalParamEnvCacheEntry) -> R, + ) -> R { + let mut cache = self.new_solver_canonical_param_env_cache.lock(); + let entry = cache.entry(param_env).or_insert_with(f); + from_entry(entry) + } + + fn assert_evaluation_is_concurrent(&self) { + // Turns out, the assumption for this function isn't perfect. + // See trait-system-refactor-initiative#234. + } + + fn expand_abstract_consts>>(self, t: T) -> T { + self.expand_abstract_consts(t) + } + + type GenericsOf = &'tcx ty::Generics; + + fn generics_of(self, def_id: DefId) -> &'tcx ty::Generics { + self.generics_of(def_id) + } + + type VariancesOf = &'tcx [ty::Variance]; + + fn variances_of(self, def_id: DefId) -> Self::VariancesOf { + self.variances_of(def_id) + } + + fn opt_alias_variances( + self, + kind: impl Into, + def_id: DefId, + ) -> Option<&'tcx [ty::Variance]> { + self.opt_alias_variances(kind, def_id) + } + + fn type_of(self, def_id: DefId) -> ty::EarlyBinder<'tcx, Ty<'tcx>> { + self.type_of(def_id) + } + fn type_of_opaque_hir_typeck(self, def_id: LocalDefId) -> ty::EarlyBinder<'tcx, Ty<'tcx>> { + self.type_of_opaque_hir_typeck(def_id) + } + fn const_of_item(self, def_id: DefId) -> ty::EarlyBinder<'tcx, Const<'tcx>> { + self.const_of_item(def_id) + } + fn anon_const_kind(self, def_id: DefId) -> ty::AnonConstKind { + self.anon_const_kind(def_id) + } + + type AdtDef = ty::AdtDef<'tcx>; + fn adt_def(self, adt_def_id: DefId) -> Self::AdtDef { + self.adt_def(adt_def_id) + } + + fn alias_ty_kind(self, alias: ty::AliasTy<'tcx>) -> ty::AliasTyKind { + match self.def_kind(alias.def_id) { + DefKind::AssocTy => { + if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(alias.def_id)) + { + ty::Inherent + } else { + ty::Projection + } + } + DefKind::OpaqueTy => ty::Opaque, + DefKind::TyAlias => ty::Free, + kind => bug!("unexpected DefKind in AliasTy: {kind:?}"), + } + } + + fn alias_term_kind(self, alias: ty::AliasTerm<'tcx>) -> ty::AliasTermKind { + match self.def_kind(alias.def_id) { + DefKind::AssocTy => { + if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(alias.def_id)) + { + ty::AliasTermKind::InherentTy + } else { + ty::AliasTermKind::ProjectionTy + } + } + DefKind::AssocConst => { + if let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(alias.def_id)) + { + ty::AliasTermKind::InherentConst + } else { + ty::AliasTermKind::ProjectionConst + } + } + DefKind::OpaqueTy => ty::AliasTermKind::OpaqueTy, + DefKind::TyAlias => ty::AliasTermKind::FreeTy, + DefKind::Const => ty::AliasTermKind::FreeConst, + DefKind::AnonConst | DefKind::Ctor(_, CtorKind::Const) => { + ty::AliasTermKind::UnevaluatedConst + } + kind => bug!("unexpected DefKind in AliasTy: {kind:?}"), + } + } + + fn trait_ref_and_own_args_for_alias( + self, + def_id: DefId, + args: ty::GenericArgsRef<'tcx>, + ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { + debug_assert_matches!(self.def_kind(def_id), DefKind::AssocTy | DefKind::AssocConst); + let trait_def_id = self.parent(def_id); + debug_assert_matches!(self.def_kind(trait_def_id), DefKind::Trait); + let trait_ref = ty::TraitRef::from_assoc(self, trait_def_id, args); + (trait_ref, &args[trait_ref.args.len()..]) + } + + fn mk_args(self, args: &[Self::GenericArg]) -> ty::GenericArgsRef<'tcx> { + self.mk_args(args) + } + + fn mk_args_from_iter(self, args: I) -> T::Output + where + I: Iterator, + T: CollectAndApply>, + { + self.mk_args_from_iter(args) + } + + fn check_args_compatible(self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> bool { + self.check_args_compatible(def_id, args) + } + + fn debug_assert_args_compatible(self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) { + self.debug_assert_args_compatible(def_id, args); + } + + /// Assert that the args from an `ExistentialTraitRef` or `ExistentialProjection` + /// are compatible with the `DefId`. Since we're missing a `Self` type, stick on + /// a dummy self type and forward to `debug_assert_args_compatible`. + fn debug_assert_existential_args_compatible( + self, + def_id: Self::DefId, + args: Self::GenericArgs, + ) { + // FIXME: We could perhaps add a `skip: usize` to `debug_assert_args_compatible` + // to avoid needing to reintern the set of args... + if cfg!(debug_assertions) { + self.debug_assert_args_compatible( + def_id, + self.mk_args_from_iter( + [self.types.trait_object_dummy_self.into()].into_iter().chain(args.iter()), + ), + ); + } + } + + fn mk_type_list_from_iter(self, args: I) -> T::Output + where + I: Iterator, + T: CollectAndApply, &'tcx List>>, + { + self.mk_type_list_from_iter(args) + } + + fn parent(self, def_id: DefId) -> DefId { + self.parent(def_id) + } + + fn recursion_limit(self) -> usize { + self.recursion_limit().0 + } + + type Features = &'tcx rustc_feature::Features; + + fn features(self) -> Self::Features { + self.features() + } + + fn coroutine_hidden_types( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, ty::Binder<'tcx, ty::CoroutineWitnessTypes>>> { + self.coroutine_hidden_types(def_id) + } + + fn fn_sig(self, def_id: DefId) -> ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>> { + self.fn_sig(def_id) + } + + fn coroutine_movability(self, def_id: DefId) -> rustc_ast::Movability { + self.coroutine_movability(def_id) + } + + fn coroutine_for_closure(self, def_id: DefId) -> DefId { + self.coroutine_for_closure(def_id) + } + + fn generics_require_sized_self(self, def_id: DefId) -> bool { + self.generics_require_sized_self(def_id) + } + + fn item_bounds( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { + self.item_bounds(def_id).map_bound(IntoIterator::into_iter) + } + + fn item_self_bounds( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { + self.item_self_bounds(def_id).map_bound(IntoIterator::into_iter) + } + + fn item_non_self_bounds( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { + self.item_non_self_bounds(def_id).map_bound(IntoIterator::into_iter) + } + + fn predicates_of( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { + ty::EarlyBinder::bind( + self.predicates_of(def_id).instantiate_identity(self).predicates.into_iter(), + ) + } + + fn own_predicates_of( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { + ty::EarlyBinder::bind( + self.predicates_of(def_id).instantiate_own_identity().map(|(clause, _)| clause), + ) + } + + fn explicit_super_predicates_of( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator, Span)>> { + self.explicit_super_predicates_of(def_id).map_bound(|preds| preds.into_iter().copied()) + } + + fn explicit_implied_predicates_of( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator, Span)>> { + self.explicit_implied_predicates_of(def_id).map_bound(|preds| preds.into_iter().copied()) + } + + fn impl_super_outlives( + self, + impl_def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator>> { + self.impl_super_outlives(impl_def_id) + } + + fn impl_is_const(self, def_id: DefId) -> bool { + debug_assert_matches!(self.def_kind(def_id), DefKind::Impl { of_trait: true }); + self.is_conditionally_const(def_id) + } + + fn fn_is_const(self, def_id: DefId) -> bool { + debug_assert_matches!( + self.def_kind(def_id), + DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) + ); + self.is_conditionally_const(def_id) + } + + fn alias_has_const_conditions(self, def_id: DefId) -> bool { + debug_assert_matches!(self.def_kind(def_id), DefKind::AssocTy | DefKind::OpaqueTy); + self.is_conditionally_const(def_id) + } + + fn const_conditions( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator>>> { + ty::EarlyBinder::bind( + self.const_conditions(def_id).instantiate_identity(self).into_iter().map(|(c, _)| c), + ) + } + + fn explicit_implied_const_bounds( + self, + def_id: DefId, + ) -> ty::EarlyBinder<'tcx, impl IntoIterator>>> { + ty::EarlyBinder::bind( + self.explicit_implied_const_bounds(def_id).iter_identity_copied().map(|(c, _)| c), + ) + } + + fn impl_self_is_guaranteed_unsized(self, impl_def_id: DefId) -> bool { + self.impl_self_is_guaranteed_unsized(impl_def_id) + } + + fn has_target_features(self, def_id: DefId) -> bool { + !self.codegen_fn_attrs(def_id).target_features.is_empty() + } + + fn require_lang_item(self, lang_item: SolverLangItem) -> DefId { + self.require_lang_item(solver_lang_item_to_lang_item(lang_item), DUMMY_SP) + } + + fn require_trait_lang_item(self, lang_item: SolverTraitLangItem) -> DefId { + self.require_lang_item(solver_trait_lang_item_to_lang_item(lang_item), DUMMY_SP) + } + + fn require_adt_lang_item(self, lang_item: SolverAdtLangItem) -> DefId { + self.require_lang_item(solver_adt_lang_item_to_lang_item(lang_item), DUMMY_SP) + } + + fn is_lang_item(self, def_id: DefId, lang_item: SolverLangItem) -> bool { + self.is_lang_item(def_id, solver_lang_item_to_lang_item(lang_item)) + } + + fn is_trait_lang_item(self, def_id: DefId, lang_item: SolverTraitLangItem) -> bool { + self.is_lang_item(def_id, solver_trait_lang_item_to_lang_item(lang_item)) + } + + fn is_adt_lang_item(self, def_id: DefId, lang_item: SolverAdtLangItem) -> bool { + self.is_lang_item(def_id, solver_adt_lang_item_to_lang_item(lang_item)) + } + + fn is_default_trait(self, def_id: DefId) -> bool { + self.is_default_trait(def_id) + } + + fn is_sizedness_trait(self, def_id: DefId) -> bool { + self.is_sizedness_trait(def_id) + } + + fn as_lang_item(self, def_id: DefId) -> Option { + lang_item_to_solver_lang_item(self.lang_items().from_def_id(def_id)?) + } + + fn as_trait_lang_item(self, def_id: DefId) -> Option { + lang_item_to_solver_trait_lang_item(self.lang_items().from_def_id(def_id)?) + } + + fn as_adt_lang_item(self, def_id: DefId) -> Option { + lang_item_to_solver_adt_lang_item(self.lang_items().from_def_id(def_id)?) + } + + fn associated_type_def_ids(self, def_id: DefId) -> impl IntoIterator { + self.associated_items(def_id) + .in_definition_order() + .filter(|assoc_item| assoc_item.is_type()) + .map(|assoc_item| assoc_item.def_id) + } + + // This implementation is a bit different from `TyCtxt::for_each_relevant_impl`, + // since we want to skip over blanket impls for non-rigid aliases, and also we + // only want to consider types that *actually* unify with float/int vars. + fn for_each_relevant_impl( + self, + trait_def_id: DefId, + self_ty: Ty<'tcx>, + mut f: impl FnMut(DefId), + ) { + let tcx = self; + let trait_impls = tcx.trait_impls_of(trait_def_id); + let mut consider_impls_for_simplified_type = |simp| { + if let Some(impls_for_type) = trait_impls.non_blanket_impls().get(&simp) { + for &impl_def_id in impls_for_type { + f(impl_def_id); + } + } + }; + + match self_ty.kind() { + ty::Bool + | ty::Char + | ty::Int(_) + | ty::Uint(_) + | ty::Float(_) + | ty::Adt(_, _) + | ty::Foreign(_) + | ty::Str + | ty::Array(_, _) + | ty::Pat(_, _) + | ty::Slice(_) + | ty::RawPtr(_, _) + | ty::Ref(_, _, _) + | ty::FnDef(_, _) + | ty::FnPtr(..) + | ty::Dynamic(_, _) + | ty::Closure(..) + | ty::CoroutineClosure(..) + | ty::Coroutine(_, _) + | ty::Never + | ty::Tuple(_) + | ty::UnsafeBinder(_) => { + if let Some(simp) = ty::fast_reject::simplify_type( + tcx, + self_ty, + ty::fast_reject::TreatParams::AsRigid, + ) { + consider_impls_for_simplified_type(simp); + } + } + + // HACK: For integer and float variables we have to manually look at all impls + // which have some integer or float as a self type. + ty::Infer(ty::IntVar(_)) => { + use ty::IntTy::*; + use ty::UintTy::*; + // This causes a compiler error if any new integer kinds are added. + let (I8 | I16 | I32 | I64 | I128 | Isize): ty::IntTy; + let (U8 | U16 | U32 | U64 | U128 | Usize): ty::UintTy; + let possible_integers = [ + // signed integers + ty::SimplifiedType::Int(I8), + ty::SimplifiedType::Int(I16), + ty::SimplifiedType::Int(I32), + ty::SimplifiedType::Int(I64), + ty::SimplifiedType::Int(I128), + ty::SimplifiedType::Int(Isize), + // unsigned integers + ty::SimplifiedType::Uint(U8), + ty::SimplifiedType::Uint(U16), + ty::SimplifiedType::Uint(U32), + ty::SimplifiedType::Uint(U64), + ty::SimplifiedType::Uint(U128), + ty::SimplifiedType::Uint(Usize), + ]; + for simp in possible_integers { + consider_impls_for_simplified_type(simp); + } + } + + ty::Infer(ty::FloatVar(_)) => { + // This causes a compiler error if any new float kinds are added. + let (ty::FloatTy::F16 | ty::FloatTy::F32 | ty::FloatTy::F64 | ty::FloatTy::F128); + let possible_floats = [ + ty::SimplifiedType::Float(ty::FloatTy::F16), + ty::SimplifiedType::Float(ty::FloatTy::F32), + ty::SimplifiedType::Float(ty::FloatTy::F64), + ty::SimplifiedType::Float(ty::FloatTy::F128), + ]; + + for simp in possible_floats { + consider_impls_for_simplified_type(simp); + } + } + + // The only traits applying to aliases and placeholders are blanket impls. + // + // Impls which apply to an alias after normalization are handled by + // `assemble_candidates_after_normalizing_self_ty`. + ty::Alias(_, _) | ty::Placeholder(..) | ty::Error(_) => (), + + // FIXME: These should ideally not exist as a self type. It would be nice for + // the builtin auto trait impls of coroutines to instead directly recurse + // into the witness. + ty::CoroutineWitness(..) => (), + + // These variants should not exist as a self type. + ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) + | ty::Param(_) + | ty::Bound(_, _) => bug!("unexpected self type: {self_ty}"), + } + + #[allow(rustc::usage_of_type_ir_traits)] + self.for_each_blanket_impl(trait_def_id, f) + } + fn for_each_blanket_impl(self, trait_def_id: DefId, mut f: impl FnMut(DefId)) { + let trait_impls = self.trait_impls_of(trait_def_id); + for &impl_def_id in trait_impls.blanket_impls() { + f(impl_def_id); + } + } + + fn has_item_definition(self, def_id: DefId) -> bool { + self.defaultness(def_id).has_value() + } + + fn impl_specializes(self, impl_def_id: Self::DefId, victim_def_id: Self::DefId) -> bool { + self.specializes((impl_def_id, victim_def_id)) + } + + fn impl_is_default(self, impl_def_id: DefId) -> bool { + self.defaultness(impl_def_id).is_default() + } + + fn impl_trait_ref(self, impl_def_id: DefId) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> { + self.impl_trait_ref(impl_def_id) + } + + fn impl_polarity(self, impl_def_id: DefId) -> ty::ImplPolarity { + self.impl_polarity(impl_def_id) + } + + fn trait_is_auto(self, trait_def_id: DefId) -> bool { + self.trait_is_auto(trait_def_id) + } + + fn trait_is_coinductive(self, trait_def_id: DefId) -> bool { + self.trait_is_coinductive(trait_def_id) + } + + fn trait_is_alias(self, trait_def_id: DefId) -> bool { + self.trait_is_alias(trait_def_id) + } + + fn trait_is_dyn_compatible(self, trait_def_id: DefId) -> bool { + self.is_dyn_compatible(trait_def_id) + } + + fn trait_is_fundamental(self, def_id: DefId) -> bool { + self.trait_def(def_id).is_fundamental + } + + fn trait_is_unsafe(self, trait_def_id: Self::DefId) -> bool { + self.trait_def(trait_def_id).safety.is_unsafe() + } + + fn is_impl_trait_in_trait(self, def_id: DefId) -> bool { + self.is_impl_trait_in_trait(def_id) + } + + fn delay_bug(self, msg: impl ToString) -> ErrorGuaranteed { + self.dcx().span_delayed_bug(DUMMY_SP, msg.to_string()) + } + + fn is_general_coroutine(self, coroutine_def_id: DefId) -> bool { + self.is_general_coroutine(coroutine_def_id) + } + + fn coroutine_is_async(self, coroutine_def_id: DefId) -> bool { + self.coroutine_is_async(coroutine_def_id) + } + + fn coroutine_is_gen(self, coroutine_def_id: DefId) -> bool { + self.coroutine_is_gen(coroutine_def_id) + } + + fn coroutine_is_async_gen(self, coroutine_def_id: DefId) -> bool { + self.coroutine_is_async_gen(coroutine_def_id) + } + + type UnsizingParams = &'tcx rustc_index::bit_set::DenseBitSet; + fn unsizing_params_for_adt(self, adt_def_id: DefId) -> Self::UnsizingParams { + self.unsizing_params_for_adt(adt_def_id) + } + + fn anonymize_bound_vars>>( + self, + binder: ty::Binder<'tcx, T>, + ) -> ty::Binder<'tcx, T> { + self.anonymize_bound_vars(binder) + } + + fn opaque_types_defined_by(self, defining_anchor: LocalDefId) -> Self::LocalDefIds { + self.opaque_types_defined_by(defining_anchor) + } + + fn opaque_types_and_coroutines_defined_by( + self, + defining_anchor: Self::LocalDefId, + ) -> Self::LocalDefIds { + let coroutines_defined_by = self + .nested_bodies_within(defining_anchor) + .iter() + .filter(|def_id| self.is_coroutine(def_id.to_def_id())); + self.mk_local_def_ids_from_iter( + self.opaque_types_defined_by(defining_anchor).iter().chain(coroutines_defined_by), + ) + } + + type Probe = &'tcx inspect::Probe>; + fn mk_probe(self, probe: inspect::Probe) -> &'tcx inspect::Probe> { + self.arena.alloc(probe) + } + fn evaluate_root_goal_for_proof_tree_raw( + self, + canonical_goal: CanonicalInput<'tcx>, + ) -> (QueryResult<'tcx>, &'tcx inspect::Probe>) { + self.evaluate_root_goal_for_proof_tree_raw(canonical_goal) + } + + fn item_name(self, id: DefId) -> Symbol { + let id = id.into_query_param(); + self.opt_item_name(id).unwrap_or_else(|| { + bug!("item_name: no name for {:?}", self.def_path(id)); + }) + } +} + +macro_rules! bidirectional_lang_item_map { + ( + $solver_ty:ident, $to_solver:ident, $from_solver:ident; + $($name:ident),+ $(,)? + ) => { + fn $from_solver(lang_item: $solver_ty) -> LangItem { + match lang_item { + $($solver_ty::$name => LangItem::$name,)+ + } + } + + fn $to_solver(lang_item: LangItem) -> Option<$solver_ty> { + Some(match lang_item { + $(LangItem::$name => $solver_ty::$name,)+ + _ => return None, + }) + } + } +} + +bidirectional_lang_item_map! { + SolverLangItem, lang_item_to_solver_lang_item, solver_lang_item_to_lang_item; + +// tidy-alphabetical-start + AsyncFnKindUpvars, + AsyncFnOnceOutput, + CallOnceFuture, + CallRefFuture, + CoroutineReturn, + CoroutineYield, + DynMetadata, + FutureOutput, + Metadata, +// tidy-alphabetical-end +} + +bidirectional_lang_item_map! { + SolverAdtLangItem, lang_item_to_solver_adt_lang_item, solver_adt_lang_item_to_lang_item; + +// tidy-alphabetical-start + Option, + Poll, +// tidy-alphabetical-end +} + +bidirectional_lang_item_map! { + SolverTraitLangItem, lang_item_to_solver_trait_lang_item, solver_trait_lang_item_to_lang_item; + +// tidy-alphabetical-start + AsyncFn, + AsyncFnKindHelper, + AsyncFnMut, + AsyncFnOnce, + AsyncFnOnceOutput, + AsyncIterator, + BikeshedGuaranteedNoDrop, + Clone, + Copy, + Coroutine, + Destruct, + DiscriminantKind, + Drop, + Fn, + FnMut, + FnOnce, + FnPtrTrait, + FusedIterator, + Future, + Iterator, + MetaSized, + PointeeSized, + PointeeTrait, + Sized, + TransmuteTrait, + TrivialClone, + Tuple, + Unpin, + Unsize, +// tidy-alphabetical-end +} From b7bfb768d0f9da6a90c32ad596fd17f57935ae87 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 8 Feb 2026 13:40:20 +1100 Subject: [PATCH 08/11] Indicate that `bidirectional_lang_item_map!` declares functions Requiring `fn` in the macro syntax makes it a little more obvious that the macro declares functions with those names, and makes them easier to grep for. --- compiler/rustc_middle/src/ty/context/impl_interner.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_middle/src/ty/context/impl_interner.rs b/compiler/rustc_middle/src/ty/context/impl_interner.rs index c449f29634e2c..5a15d132048dd 100644 --- a/compiler/rustc_middle/src/ty/context/impl_interner.rs +++ b/compiler/rustc_middle/src/ty/context/impl_interner.rs @@ -722,9 +722,11 @@ impl<'tcx> Interner for TyCtxt<'tcx> { } } +/// Defines trivial conversion functions between the main [`LangItem`] enum, +/// and some other lang-item enum that is a subset of it. macro_rules! bidirectional_lang_item_map { ( - $solver_ty:ident, $to_solver:ident, $from_solver:ident; + $solver_ty:ident, fn $to_solver:ident, fn $from_solver:ident; $($name:ident),+ $(,)? ) => { fn $from_solver(lang_item: $solver_ty) -> LangItem { @@ -743,7 +745,7 @@ macro_rules! bidirectional_lang_item_map { } bidirectional_lang_item_map! { - SolverLangItem, lang_item_to_solver_lang_item, solver_lang_item_to_lang_item; + SolverLangItem, fn lang_item_to_solver_lang_item, fn solver_lang_item_to_lang_item; // tidy-alphabetical-start AsyncFnKindUpvars, @@ -759,7 +761,7 @@ bidirectional_lang_item_map! { } bidirectional_lang_item_map! { - SolverAdtLangItem, lang_item_to_solver_adt_lang_item, solver_adt_lang_item_to_lang_item; + SolverAdtLangItem, fn lang_item_to_solver_adt_lang_item, fn solver_adt_lang_item_to_lang_item; // tidy-alphabetical-start Option, @@ -768,7 +770,7 @@ bidirectional_lang_item_map! { } bidirectional_lang_item_map! { - SolverTraitLangItem, lang_item_to_solver_trait_lang_item, solver_trait_lang_item_to_lang_item; + SolverTraitLangItem, fn lang_item_to_solver_trait_lang_item, fn solver_trait_lang_item_to_lang_item; // tidy-alphabetical-start AsyncFn, From 4dc82e99efad0d0fbb91218b82394a48fcd0ed87 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 5 Feb 2026 18:21:27 +1100 Subject: [PATCH 09/11] Move the needs-drop check for `arena_cache` queries out of macro code --- compiler/rustc_middle/src/queries.rs | 1 - .../rustc_middle/src/query/arena_cached.rs | 33 +++++++++----- compiler/rustc_middle/src/query/plumbing.rs | 44 ++++++++----------- 3 files changed, 40 insertions(+), 38 deletions(-) diff --git a/compiler/rustc_middle/src/queries.rs b/compiler/rustc_middle/src/queries.rs index de22989144389..2fdc44ecd2691 100644 --- a/compiler/rustc_middle/src/queries.rs +++ b/compiler/rustc_middle/src/queries.rs @@ -63,7 +63,6 @@ #![allow(unused_parens)] use std::ffi::OsStr; -use std::mem; use std::path::PathBuf; use std::sync::Arc; diff --git a/compiler/rustc_middle/src/query/arena_cached.rs b/compiler/rustc_middle/src/query/arena_cached.rs index ec6e466ff688c..7c7ad12622604 100644 --- a/compiler/rustc_middle/src/query/arena_cached.rs +++ b/compiler/rustc_middle/src/query/arena_cached.rs @@ -1,3 +1,9 @@ +use std::mem; + +use rustc_arena::TypedArena; + +use crate::ty::TyCtxt; + /// Helper trait that allows `arena_cache` queries to return `Option<&T>` /// instead of `&Option`, and avoid allocating `None` in the arena. /// @@ -11,10 +17,11 @@ pub trait ArenaCached<'tcx>: Sized { /// Type that is stored in the arena. type Allocated: 'tcx; - /// Takes a provided value, and allocates it in the arena (if appropriate) - /// with the help of the given `arena_alloc` closure. + /// Takes a provided value, and allocates it in an appropriate arena, + /// unless the particular value doesn't need allocation (e.g. `None`). fn alloc_in_arena( - arena_alloc: impl Fn(Self::Allocated) -> &'tcx Self::Allocated, + tcx: TyCtxt<'tcx>, + typed_arena: &'tcx TypedArena, value: Self::Provided, ) -> Self; } @@ -23,12 +30,9 @@ impl<'tcx, T> ArenaCached<'tcx> for &'tcx T { type Provided = T; type Allocated = T; - fn alloc_in_arena( - arena_alloc: impl Fn(Self::Allocated) -> &'tcx Self::Allocated, - value: Self::Provided, - ) -> Self { + fn alloc_in_arena(tcx: TyCtxt<'tcx>, typed_arena: &'tcx TypedArena, value: T) -> Self { // Just allocate in the arena normally. - arena_alloc(value) + do_alloc(tcx, typed_arena, value) } } @@ -38,10 +42,17 @@ impl<'tcx, T> ArenaCached<'tcx> for Option<&'tcx T> { type Allocated = T; fn alloc_in_arena( - arena_alloc: impl Fn(Self::Allocated) -> &'tcx Self::Allocated, - value: Self::Provided, + tcx: TyCtxt<'tcx>, + typed_arena: &'tcx TypedArena, + value: Option, ) -> Self { // Don't store None in the arena, and wrap the allocated reference in Some. - value.map(arena_alloc) + try { do_alloc(tcx, typed_arena, value?) } } } + +/// Allocates a value in either its dedicated arena, or in the common dropless +/// arena, depending on whether it needs to be dropped. +fn do_alloc<'tcx, T>(tcx: TyCtxt<'tcx>, typed_arena: &'tcx TypedArena, value: T) -> &'tcx T { + if mem::needs_drop::() { typed_arena.alloc(value) } else { tcx.arena.dropless.alloc(value) } +} diff --git a/compiler/rustc_middle/src/query/plumbing.rs b/compiler/rustc_middle/src/query/plumbing.rs index 04a3ceb0918af..b80f096ec9935 100644 --- a/compiler/rustc_middle/src/query/plumbing.rs +++ b/compiler/rustc_middle/src/query/plumbing.rs @@ -295,36 +295,28 @@ macro_rules! define_callbacks { ($V) ); - /// This function takes `ProvidedValue` and converts it to an erased `Value` by - /// allocating it on an arena if the query has the `arena_cache` modifier. The - /// value is then erased and returned. This will happen when computing the query - /// using a provider or decoding a stored result. + /// This helper function takes a value returned by the query provider + /// (or loaded from disk, or supplied by query feeding), allocates + /// it in an arena if requested by the `arena_cache` modifier, and + /// then returns an erased copy of it. #[inline(always)] pub fn provided_to_erased<'tcx>( - _tcx: TyCtxt<'tcx>, + tcx: TyCtxt<'tcx>, provided_value: ProvidedValue<'tcx>, ) -> Erased> { - // Store the provided value in an arena and get a reference - // to it, for queries with `arena_cache`. - let value: Value<'tcx> = query_if_arena!([$($modifiers)*] - { - use $crate::query::arena_cached::ArenaCached; - - if mem::needs_drop::<<$V as ArenaCached<'tcx>>::Allocated>() { - <$V as ArenaCached>::alloc_in_arena( - |v| _tcx.query_system.arenas.$name.alloc(v), - provided_value, - ) - } else { - <$V as ArenaCached>::alloc_in_arena( - |v| _tcx.arena.dropless.alloc(v), - provided_value, - ) - } - } - // Otherwise, the provided value is the value. - (provided_value) - ); + // For queries with the `arena_cache` modifier, store the + // provided value in an arena and get a reference to it. + let value: Value<'tcx> = query_if_arena!([$($modifiers)*] { + <$V as $crate::query::arena_cached::ArenaCached>::alloc_in_arena( + tcx, + &tcx.query_system.arenas.$name, + provided_value, + ) + } { + // Otherwise, the provided value is the value (and `tcx` is unused). + let _ = tcx; + provided_value + }); erase::erase_val(value) } From 20f65fc537e26bd92e0da4088c27e5905c3fc52a Mon Sep 17 00:00:00 2001 From: Shoyu Vanilla Date: Tue, 10 Feb 2026 01:31:48 +0900 Subject: [PATCH 10/11] Uplift `Predicate::allow_normalization` to `rustc_type_ir` --- compiler/rustc_middle/src/ty/predicate.rs | 24 +--------------------- compiler/rustc_type_ir/src/inherent.rs | 25 ++++++++++++++++++++--- 2 files changed, 23 insertions(+), 26 deletions(-) diff --git a/compiler/rustc_middle/src/ty/predicate.rs b/compiler/rustc_middle/src/ty/predicate.rs index 69dcca54f469d..3baeb7141de50 100644 --- a/compiler/rustc_middle/src/ty/predicate.rs +++ b/compiler/rustc_middle/src/ty/predicate.rs @@ -49,10 +49,6 @@ impl<'tcx> rustc_type_ir::inherent::Predicate> for Predicate<'tcx> fn as_clause(self) -> Option> { self.as_clause() } - - fn allow_normalization(self) -> bool { - self.allow_normalization() - } } impl<'tcx> rustc_type_ir::inherent::IntoKind for Predicate<'tcx> { @@ -121,25 +117,7 @@ impl<'tcx> Predicate<'tcx> { /// unsoundly accept some programs. See #91068. #[inline] pub fn allow_normalization(self) -> bool { - match self.kind().skip_binder() { - PredicateKind::Clause(ClauseKind::WellFormed(_)) | PredicateKind::AliasRelate(..) => { - false - } - PredicateKind::Clause(ClauseKind::Trait(_)) - | PredicateKind::Clause(ClauseKind::HostEffect(..)) - | PredicateKind::Clause(ClauseKind::RegionOutlives(_)) - | PredicateKind::Clause(ClauseKind::TypeOutlives(_)) - | PredicateKind::Clause(ClauseKind::Projection(_)) - | PredicateKind::Clause(ClauseKind::ConstArgHasType(..)) - | PredicateKind::Clause(ClauseKind::UnstableFeature(_)) - | PredicateKind::DynCompatible(_) - | PredicateKind::Subtype(_) - | PredicateKind::Coerce(_) - | PredicateKind::Clause(ClauseKind::ConstEvaluatable(_)) - | PredicateKind::ConstEquate(_, _) - | PredicateKind::NormalizesTo(..) - | PredicateKind::Ambiguous => true, - } + rustc_type_ir::inherent::Predicate::allow_normalization(self) } } diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index 89cb236d38c6d..c9580d589d217 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -13,7 +13,7 @@ use crate::fold::{TypeFoldable, TypeSuperFoldable}; use crate::relate::Relate; use crate::solve::{AdtDestructorKind, SizedTraitKind}; use crate::visit::{Flags, TypeSuperVisitable, TypeVisitable}; -use crate::{self as ty, CollectAndApply, Interner, UpcastFrom}; +use crate::{self as ty, ClauseKind, CollectAndApply, Interner, PredicateKind, UpcastFrom}; pub trait Ty>: Copy @@ -478,8 +478,27 @@ pub trait Predicate>: } } - // FIXME: Eventually uplift the impl out of rustc and make this defaulted. - fn allow_normalization(self) -> bool; + fn allow_normalization(self) -> bool { + match self.kind().skip_binder() { + PredicateKind::Clause(ClauseKind::WellFormed(_)) | PredicateKind::AliasRelate(..) => { + false + } + PredicateKind::Clause(ClauseKind::Trait(_)) + | PredicateKind::Clause(ClauseKind::HostEffect(..)) + | PredicateKind::Clause(ClauseKind::RegionOutlives(_)) + | PredicateKind::Clause(ClauseKind::TypeOutlives(_)) + | PredicateKind::Clause(ClauseKind::Projection(_)) + | PredicateKind::Clause(ClauseKind::ConstArgHasType(..)) + | PredicateKind::Clause(ClauseKind::UnstableFeature(_)) + | PredicateKind::DynCompatible(_) + | PredicateKind::Subtype(_) + | PredicateKind::Coerce(_) + | PredicateKind::Clause(ClauseKind::ConstEvaluatable(_)) + | PredicateKind::ConstEquate(_, _) + | PredicateKind::NormalizesTo(..) + | PredicateKind::Ambiguous => true, + } + } } pub trait Clause>: From d215efd5aaf08d170de0086eacd01a6513259c90 Mon Sep 17 00:00:00 2001 From: Oscar Bray Date: Tue, 10 Feb 2026 08:13:09 +0000 Subject: [PATCH 11/11] Port #![test_runner] to the attribute parser --- .../src/attributes/test_attrs.rs | 29 +++++++++++++++++ compiler/rustc_attr_parsing/src/context.rs | 1 + compiler/rustc_builtin_macros/src/errors.rs | 14 --------- .../rustc_builtin_macros/src/test_harness.rs | 31 +++++++++---------- .../rustc_hir/src/attrs/data_structures.rs | 5 ++- .../rustc_hir/src/attrs/encode_cross_crate.rs | 1 + .../rustc_hir/src/attrs/pretty_printing.rs | 11 +++++++ compiler/rustc_passes/src/check_attr.rs | 5 ++- 8 files changed, 62 insertions(+), 35 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs index 18d700a20d319..41b1836588deb 100644 --- a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs @@ -228,3 +228,32 @@ impl NoArgsAttributeParser for RustcOutlivesParser { ]); const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcOutlives; } + +pub(crate) struct TestRunnerParser; + +impl SingleAttributeParser for TestRunnerParser { + const PATH: &[Symbol] = &[sym::test_runner]; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]); + const TEMPLATE: AttributeTemplate = template!(List: &["path"]); + + fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option { + let Some(list) = args.list() else { + cx.expected_list(cx.attr_span, args); + return None; + }; + + let Some(single) = list.single() else { + cx.expected_single_argument(list.span); + return None; + }; + + let Some(meta) = single.meta_item() else { + cx.unexpected_literal(single.span()); + return None; + }; + + Some(AttributeKind::TestRunner(meta.path().0.clone())) + } +} diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 412f960fb7cfb..c9d8e07a4578a 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -216,6 +216,7 @@ attribute_parsers!( Single, Single, Single, + Single, Single, Single, Single, diff --git a/compiler/rustc_builtin_macros/src/errors.rs b/compiler/rustc_builtin_macros/src/errors.rs index 1343c8ccf4a59..862ce3e62cc95 100644 --- a/compiler/rustc_builtin_macros/src/errors.rs +++ b/compiler/rustc_builtin_macros/src/errors.rs @@ -1002,20 +1002,6 @@ pub(crate) struct AsmUnsupportedClobberAbi { pub(crate) macro_name: &'static str, } -#[derive(Diagnostic)] -#[diag("`test_runner` argument must be a path")] -pub(crate) struct TestRunnerInvalid { - #[primary_span] - pub(crate) span: Span, -} - -#[derive(Diagnostic)] -#[diag("`#![test_runner(..)]` accepts exactly 1 argument")] -pub(crate) struct TestRunnerNargs { - #[primary_span] - pub(crate) span: Span, -} - #[derive(Diagnostic)] #[diag("expected token: `,`")] pub(crate) struct ExpectedCommaInList { diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index 8d6969b0ca125..b5d63511fce9b 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -8,10 +8,11 @@ use rustc_ast::entry::EntryPointType; use rustc_ast::mut_visit::*; use rustc_ast::visit::Visitor; use rustc_ast::{ModKind, attr}; -use rustc_errors::DiagCtxtHandle; +use rustc_attr_parsing::AttributeParser; use rustc_expand::base::{ExtCtxt, ResolverExpand}; use rustc_expand::expand::{AstFragment, ExpansionConfig}; use rustc_feature::Features; +use rustc_hir::attrs::AttributeKind; use rustc_session::Session; use rustc_session::lint::builtin::UNNAMEABLE_TEST_ITEMS; use rustc_span::hygiene::{AstPass, SyntaxContext, Transparency}; @@ -60,7 +61,7 @@ pub fn inject( // Do this here so that the test_runner crate attribute gets marked as used // even in non-test builds - let test_runner = get_test_runner(dcx, krate); + let test_runner = get_test_runner(sess, features, krate); if sess.is_test_crate() { let panic_strategy = match (panic_strategy, sess.opts.unstable_opts.panic_abort_tests) { @@ -386,20 +387,16 @@ fn get_test_name(i: &ast::Item) -> Option { attr::first_attr_value_str_by_name(&i.attrs, sym::rustc_test_marker) } -fn get_test_runner(dcx: DiagCtxtHandle<'_>, krate: &ast::Crate) -> Option { - let test_attr = attr::find_by_name(&krate.attrs, sym::test_runner)?; - let meta_list = test_attr.meta_item_list()?; - let span = test_attr.span; - match &*meta_list { - [single] => match single.meta_item() { - Some(meta_item) if meta_item.is_word() => return Some(meta_item.path.clone()), - _ => { - dcx.emit_err(errors::TestRunnerInvalid { span }); - } - }, - _ => { - dcx.emit_err(errors::TestRunnerNargs { span }); - } +fn get_test_runner(sess: &Session, features: &Features, krate: &ast::Crate) -> Option { + match AttributeParser::parse_limited( + sess, + &krate.attrs, + sym::test_runner, + krate.spans.inner_span, + krate.id, + Some(features), + ) { + Some(rustc_hir::Attribute::Parsed(AttributeKind::TestRunner(path))) => Some(path), + _ => None, } - None } diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index 2d3825ccd0246..804e43541f9ea 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -5,7 +5,7 @@ pub use ReprAttr::*; use rustc_abi::Align; pub use rustc_ast::attr::data_structures::*; use rustc_ast::token::DocFragmentKind; -use rustc_ast::{AttrStyle, ast}; +use rustc_ast::{AttrStyle, Path, ast}; use rustc_data_structures::fx::FxIndexMap; use rustc_error_messages::{DiagArgValue, IntoDiagArg}; use rustc_macros::{Decodable, Encodable, HashStable_Generic, PrintAttribute}; @@ -1292,6 +1292,9 @@ pub enum AttributeKind { /// `#[unsafe(force_target_feature(enable = "...")]`. TargetFeature { features: ThinVec<(Symbol, Span)>, attr_span: Span, was_forced: bool }, + /// Represents `#![test_runner(path)]` + TestRunner(Path), + /// Represents `#[thread_local]` ThreadLocal, diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index ac9ef79e9ab92..e4a06cf10038e 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -169,6 +169,7 @@ impl AttributeKind { ShouldPanic { .. } => No, Stability { .. } => Yes, TargetFeature { .. } => No, + TestRunner(..) => Yes, ThreadLocal => No, TrackCaller(..) => Yes, TypeLengthLimit { .. } => No, diff --git a/compiler/rustc_hir/src/attrs/pretty_printing.rs b/compiler/rustc_hir/src/attrs/pretty_printing.rs index 20efd72e20f7f..8fce529010150 100644 --- a/compiler/rustc_hir/src/attrs/pretty_printing.rs +++ b/compiler/rustc_hir/src/attrs/pretty_printing.rs @@ -3,6 +3,7 @@ use std::ops::Deref; use std::path::PathBuf; use rustc_abi::Align; +use rustc_ast::ast::{Path, join_path_idents}; use rustc_ast::attr::data_structures::CfgEntry; use rustc_ast::attr::version::RustcVersion; use rustc_ast::token::{CommentKind, DocFragmentKind}; @@ -106,6 +107,16 @@ impl PrintAttribute for PathBuf { p.word(self.display().to_string()); } } +impl PrintAttribute for Path { + fn should_render(&self) -> bool { + true + } + + fn print_attribute(&self, p: &mut Printer) { + p.word(join_path_idents(self.segments.iter().map(|seg| seg.ident))); + } +} + macro_rules! print_skip { ($($t: ty),* $(,)?) => {$( impl PrintAttribute for $t { diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 0ba4450b17229..ec6139a8071cf 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -357,6 +357,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcVariance | AttributeKind::RustcVarianceOfOpaques | AttributeKind::ShouldPanic { .. } + | AttributeKind::TestRunner(..) | AttributeKind::ThreadLocal | AttributeKind::TypeLengthLimit { .. } | AttributeKind::UnstableFeatureBound(..) @@ -412,9 +413,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::rustc_expected_cgu_reuse // crate-level attrs, are checked below | sym::feature - | sym::register_tool - | sym::test_runner, - .. + | sym::register_tool, .. ] => {} [name, rest@..] => { match BUILTIN_ATTRIBUTE_MAP.get(name) {