1// This file contains various trait resolution methods used by codegen.
2// They all assume regions can be erased and monomorphic types. It
3// seems likely that they should eventually be merged into more
4// general routines.
56use rustc_infer::infer::TyCtxtInferExt;
7use rustc_middle::bug;
8use rustc_middle::traits::CodegenObligationError;
9use rustc_middle::ty::{self, PseudoCanonicalInput, TyCtxt, TypeVisitableExt, Unnormalized};
10use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
11use rustc_trait_selection::traits::{
12ImplSource, Obligation, ObligationCause, ObligationCtxt, ScrubbedTraitError, SelectionContext,
13SelectionError,
14};
15use tracing::debug;
1617/// Attempts to resolve an obligation to an `ImplSource`. The result is
18/// a shallow `ImplSource` resolution, meaning that we do not
19/// (necessarily) resolve all nested obligations on the impl. Note
20/// that type check should guarantee to us that all nested
21/// obligations *could be* resolved if we wanted to.
22///
23/// This also expects that `trait_ref` is fully normalized.
24pub(crate) fn codegen_select_candidate<'tcx>(
25 tcx: TyCtxt<'tcx>,
26 key: PseudoCanonicalInput<'tcx, ty::TraitRef<'tcx>>,
27) -> Result<&'tcx ImplSource<'tcx, ()>, CodegenObligationError> {
28let PseudoCanonicalInput { typing_env, value: trait_ref } = key;
29// We expect the input to be fully normalized.
30if true {
match (&trait_ref,
&tcx.normalize_erasing_regions(typing_env,
Unnormalized::new_wip(trait_ref))) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(
31 trait_ref,
32 tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(trait_ref))
33 );
3435// Do the initial selection for the obligation. This yields the
36 // shallow result we are looking for -- that is, what specific impl.
37let (infcx, param_env) = tcx.infer_ctxt().ignoring_regions().build_with_typing_env(typing_env);
38let mut selcx = SelectionContext::new(&infcx);
3940let obligation_cause = ObligationCause::dummy();
41let obligation = Obligation::new(tcx, obligation_cause, param_env, trait_ref);
4243let selection = match selcx.select(&obligation) {
44Ok(Some(selection)) => selection,
45Ok(None) => return Err(CodegenObligationError::Ambiguity),
46Err(SelectionError::Unimplemented) => return Err(CodegenObligationError::Unimplemented),
47Err(e) => {
48::rustc_middle::util::bug::bug_fmt(format_args!("Encountered error `{0:?}` selecting `{1:?}` during codegen",
e, trait_ref))bug!("Encountered error `{:?}` selecting `{:?}` during codegen", e, trait_ref)49 }
50 };
5152{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_traits/src/codegen.rs:52",
"rustc_traits::codegen", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_traits/src/codegen.rs"),
::tracing_core::__macro_support::Option::Some(52u32),
::tracing_core::__macro_support::Option::Some("rustc_traits::codegen"),
::tracing_core::field::FieldSet::new(&["selection"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&selection)
as &dyn Value))])
});
} else { ; }
};debug!(?selection);
5354// Currently, we use a fulfillment context to completely resolve
55 // all nested obligations. This is because they can inform the
56 // inference of the impl's type parameters.
57let ocx = ObligationCtxt::new(&infcx);
58let impl_source = selection.map(|obligation| {
59ocx.register_obligation(obligation);
60 });
6162// In principle, we only need to do this so long as `impl_source`
63 // contains unbound type parameters. It could be a slight
64 // optimization to stop iterating early.
65let errors = ocx.evaluate_obligations_error_on_ambiguity();
66if !errors.is_empty() {
67// `rustc_monomorphize::collector` assumes there are no type errors.
68 // Cycle errors are the only post-monomorphization errors possible; emit them now so
69 // `rustc_ty_utils::resolve_associated_item` doesn't return `None` post-monomorphization.
70for err in errors {
71if let ScrubbedTraitError::Cycle(cycle) = err {
72 infcx.err_ctxt().report_overflow_obligation_cycle(&cycle);
73 }
74 }
75return Err(CodegenObligationError::Unimplemented);
76 }
7778let impl_source = infcx.resolve_vars_if_possible(impl_source);
79let impl_source = tcx.erase_and_anonymize_regions(impl_source);
80if impl_source.has_non_region_infer() {
81// Unused generic types or consts on an impl get replaced with inference vars,
82 // but never resolved, causing the return value of a query to contain inference
83 // vars. We do not have a concept for this and will in fact ICE in stable hashing
84 // of the return value. So bail out instead.
85let guar = match impl_source {
86 ImplSource::UserDefined(impl_) => tcx.dcx().span_delayed_bug(
87tcx.def_span(impl_.impl_def_id),
88"this impl has unconstrained generic parameters",
89 ),
90_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
91 };
92return Err(CodegenObligationError::UnconstrainedParam(guar));
93 }
9495Ok(&*tcx.arena.alloc(impl_source))
96}