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};
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, 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!(trait_ref, tcx.normalize_erasing_regions(typing_env, trait_ref));
3132// Do the initial selection for the obligation. This yields the
33 // shallow result we are looking for -- that is, what specific impl.
34let (infcx, param_env) = tcx.infer_ctxt().ignoring_regions().build_with_typing_env(typing_env);
35let mut selcx = SelectionContext::new(&infcx);
3637let obligation_cause = ObligationCause::dummy();
38let obligation = Obligation::new(tcx, obligation_cause, param_env, trait_ref);
3940let selection = match selcx.select(&obligation) {
41Ok(Some(selection)) => selection,
42Ok(None) => return Err(CodegenObligationError::Ambiguity),
43Err(SelectionError::Unimplemented) => return Err(CodegenObligationError::Unimplemented),
44Err(e) => {
45::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)46 }
47 };
4849{
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:49",
"rustc_traits::codegen", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_traits/src/codegen.rs"),
::tracing_core::__macro_support::Option::Some(49u32),
::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);
5051// Currently, we use a fulfillment context to completely resolve
52 // all nested obligations. This is because they can inform the
53 // inference of the impl's type parameters.
54let ocx = ObligationCtxt::new(&infcx);
55let impl_source = selection.map(|obligation| {
56ocx.register_obligation(obligation);
57 });
5859// In principle, we only need to do this so long as `impl_source`
60 // contains unbound type parameters. It could be a slight
61 // optimization to stop iterating early.
62let errors = ocx.evaluate_obligations_error_on_ambiguity();
63if !errors.is_empty() {
64// `rustc_monomorphize::collector` assumes there are no type errors.
65 // Cycle errors are the only post-monomorphization errors possible; emit them now so
66 // `rustc_ty_utils::resolve_associated_item` doesn't return `None` post-monomorphization.
67for err in errors {
68if let ScrubbedTraitError::Cycle(cycle) = err {
69 infcx.err_ctxt().report_overflow_obligation_cycle(&cycle);
70 }
71 }
72return Err(CodegenObligationError::Unimplemented);
73 }
7475let impl_source = infcx.resolve_vars_if_possible(impl_source);
76let impl_source = tcx.erase_and_anonymize_regions(impl_source);
77if impl_source.has_non_region_infer() {
78// Unused generic types or consts on an impl get replaced with inference vars,
79 // but never resolved, causing the return value of a query to contain inference
80 // vars. We do not have a concept for this and will in fact ICE in stable hashing
81 // of the return value. So bail out instead.
82let guar = match impl_source {
83 ImplSource::UserDefined(impl_) => tcx.dcx().span_delayed_bug(
84tcx.def_span(impl_.impl_def_id),
85"this impl has unconstrained generic parameters",
86 ),
87_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
88 };
89return Err(CodegenObligationError::UnconstrainedParam(guar));
90 }
9192Ok(&*tcx.arena.alloc(impl_source))
93}