rustc_traits/
codegen.rs

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.
5
6use 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    SelectionError, sizedness_fast_path,
14};
15use tracing::debug;
16
17/// 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> {
28    let PseudoCanonicalInput { typing_env, value: trait_ref } = key;
29    // We expect the input to be fully normalized.
30    debug_assert_eq!(trait_ref, tcx.normalize_erasing_regions(typing_env, trait_ref));
31
32    // Do the initial selection for the obligation. This yields the
33    // shallow result we are looking for -- that is, what specific impl.
34    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(SelectionError::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    // Currently, we use a fulfillment context to completely resolve
59    // all nested obligations. This is because they can inform the
60    // inference of the impl's type parameters.
61    let ocx = ObligationCtxt::new(&infcx);
62    let impl_source = selection.map(|obligation| {
63        ocx.register_obligation(obligation);
64    });
65
66    // In principle, we only need to do this so long as `impl_source`
67    // contains unbound type parameters. It could be a slight
68    // optimization to stop iterating early.
69    let errors = ocx.select_all_or_error();
70    if !errors.is_empty() {
71        // `rustc_monomorphize::collector` assumes there are no type errors.
72        // Cycle errors are the only post-monomorphization errors possible; emit them now so
73        // `rustc_ty_utils::resolve_associated_item` doesn't return `None` post-monomorphization.
74        for err in errors {
75            if let ScrubbedTraitError::Cycle(cycle) = err {
76                infcx.err_ctxt().report_overflow_obligation_cycle(&cycle);
77            }
78        }
79        return Err(CodegenObligationError::Unimplemented);
80    }
81
82    let impl_source = infcx.resolve_vars_if_possible(impl_source);
83    let impl_source = tcx.erase_regions(impl_source);
84    if impl_source.has_non_region_infer() {
85        // Unused generic types or consts on an impl get replaced with inference vars,
86        // but never resolved, causing the return value of a query to contain inference
87        // vars. We do not have a concept for this and will in fact ICE in stable hashing
88        // of the return value. So bail out instead.
89        let guar = match impl_source {
90            ImplSource::UserDefined(impl_) => tcx.dcx().span_delayed_bug(
91                tcx.def_span(impl_.impl_def_id),
92                "this impl has unconstrained generic parameters",
93            ),
94            _ => unreachable!(),
95        };
96        return Err(CodegenObligationError::UnconstrainedParam(guar));
97    }
98
99    Ok(&*tcx.arena.alloc(impl_source))
100}