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, Unnormalized};
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,
                    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    );
34
35    // Do the initial selection for the obligation. This yields the
36    // shallow result we are looking for -- that is, what specific impl.
37    let (infcx, param_env) = tcx.infer_ctxt().ignoring_regions().build_with_typing_env(typing_env);
38    let mut selcx = SelectionContext::new(&infcx);
39
40    let obligation_cause = ObligationCause::dummy();
41    let obligation = Obligation::new(tcx, obligation_cause, param_env, trait_ref);
42
43    let selection = match selcx.select(&obligation) {
44        Ok(Some(selection)) => selection,
45        Ok(None) => return Err(CodegenObligationError::Ambiguity),
46        Err(SelectionError::Unimplemented) => return Err(CodegenObligationError::Unimplemented),
47        Err(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    };
51
52    {
    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);
53
54    // 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.
57    let ocx = ObligationCtxt::new(&infcx);
58    let impl_source = selection.map(|obligation| {
59        ocx.register_obligation(obligation);
60    });
61
62    // 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.
65    let errors = ocx.evaluate_obligations_error_on_ambiguity();
66    if !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.
70        for err in errors {
71            if let ScrubbedTraitError::Cycle(cycle) = err {
72                infcx.err_ctxt().report_overflow_obligation_cycle(&cycle);
73            }
74        }
75        return Err(CodegenObligationError::Unimplemented);
76    }
77
78    let impl_source = infcx.resolve_vars_if_possible(impl_source);
79    let impl_source = tcx.erase_and_anonymize_regions(impl_source);
80    if 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.
85        let guar = match impl_source {
86            ImplSource::UserDefined(impl_) => tcx.dcx().span_delayed_bug(
87                tcx.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        };
92        return Err(CodegenObligationError::UnconstrainedParam(guar));
93    }
94
95    Ok(&*tcx.arena.alloc(impl_source))
96}