1use rustc_infer::infer::TyCtxtInferExt;
7use rustc_middle::bug;
8use rustc_middle::traits::CodegenObligationError;
9use rustc_middle::ty::{self, PseudoCanonicalInput, TyCtxt, TypeVisitableExt, Upcast};
10use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
11use rustc_trait_selection::traits::{
12 ImplSource, Obligation, ObligationCause, ObligationCtxt, ScrubbedTraitError, SelectionContext,
13 Unimplemented, sizedness_fast_path,
14};
15use tracing::debug;
16
17pub(crate) fn codegen_select_candidate<'tcx>(
25 tcx: TyCtxt<'tcx>,
26 key: PseudoCanonicalInput<'tcx, ty::TraitRef<'tcx>>,
27) -> Result<&'tcx ImplSource<'tcx, ()>, CodegenObligationError> {
28 let PseudoCanonicalInput { typing_env, value: trait_ref } = key;
29 debug_assert_eq!(trait_ref, tcx.normalize_erasing_regions(typing_env, trait_ref));
31
32 let (infcx, param_env) = tcx.infer_ctxt().ignoring_regions().build_with_typing_env(typing_env);
35 let mut selcx = SelectionContext::new(&infcx);
36
37 if sizedness_fast_path(tcx, trait_ref.upcast(tcx)) {
38 return Ok(&*tcx.arena.alloc(ImplSource::Builtin(
39 ty::solve::BuiltinImplSource::Trivial,
40 Default::default(),
41 )));
42 }
43
44 let obligation_cause = ObligationCause::dummy();
45 let obligation = Obligation::new(tcx, obligation_cause, param_env, trait_ref);
46
47 let selection = match selcx.select(&obligation) {
48 Ok(Some(selection)) => selection,
49 Ok(None) => return Err(CodegenObligationError::Ambiguity),
50 Err(Unimplemented) => return Err(CodegenObligationError::Unimplemented),
51 Err(e) => {
52 bug!("Encountered error `{:?}` selecting `{:?}` during codegen", e, trait_ref)
53 }
54 };
55
56 debug!(?selection);
57
58 let ocx = ObligationCtxt::new(&infcx);
63 let impl_source = selection.map(|obligation| {
64 ocx.register_obligation(obligation);
65 });
66
67 let errors = ocx.select_all_or_error();
71 if !errors.is_empty() {
72 for err in errors {
76 if let ScrubbedTraitError::Cycle(cycle) = err {
77 infcx.err_ctxt().report_overflow_obligation_cycle(&cycle);
78 }
79 }
80 return Err(CodegenObligationError::Unimplemented);
81 }
82
83 let impl_source = infcx.resolve_vars_if_possible(impl_source);
84 let impl_source = tcx.erase_regions(impl_source);
85 if impl_source.has_non_region_infer() {
86 let guar = match impl_source {
91 ImplSource::UserDefined(impl_) => tcx.dcx().span_delayed_bug(
92 tcx.def_span(impl_.impl_def_id),
93 "this impl has unconstrained generic parameters",
94 ),
95 _ => unreachable!(),
96 };
97 return Err(CodegenObligationError::UnconstrainedParam(guar));
98 }
99
100 Ok(&*tcx.arena.alloc(impl_source))
101}