Skip to main content

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};
10use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
11use rustc_trait_selection::traits::{
12    ImplSource, Obligation, ObligationCause, ObligationCtxt, ScrubbedTraitError, SelectionContext,
13    SelectionError,
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    if 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));
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    let obligation_cause = ObligationCause::dummy();
38    let obligation = Obligation::new(tcx, obligation_cause, param_env, trait_ref);
39
40    let selection = match selcx.select(&obligation) {
41        Ok(Some(selection)) => selection,
42        Ok(None) => return Err(CodegenObligationError::Ambiguity),
43        Err(SelectionError::Unimplemented) => return Err(CodegenObligationError::Unimplemented),
44        Err(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    };
48
49    {
    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);
50
51    // 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.
54    let ocx = ObligationCtxt::new(&infcx);
55    let impl_source = selection.map(|obligation| {
56        ocx.register_obligation(obligation);
57    });
58
59    // 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.
62    let errors = ocx.evaluate_obligations_error_on_ambiguity();
63    if !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.
67        for err in errors {
68            if let ScrubbedTraitError::Cycle(cycle) = err {
69                infcx.err_ctxt().report_overflow_obligation_cycle(&cycle);
70            }
71        }
72        return Err(CodegenObligationError::Unimplemented);
73    }
74
75    let impl_source = infcx.resolve_vars_if_possible(impl_source);
76    let impl_source = tcx.erase_and_anonymize_regions(impl_source);
77    if 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.
82        let guar = match impl_source {
83            ImplSource::UserDefined(impl_) => tcx.dcx().span_delayed_bug(
84                tcx.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        };
89        return Err(CodegenObligationError::UnconstrainedParam(guar));
90    }
91
92    Ok(&*tcx.arena.alloc(impl_source))
93}