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::traits::CodegenObligationError;
8use rustc_middle::ty::{self, PseudoCanonicalInput, TyCtxt, TypeVisitableExt};
9use rustc_span::bug;
10use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
11use rustc_trait_selection::traits::{
12    FulfillmentErrorCode, ImplSource, Obligation, ObligationCause, ObligationCtxt,
13    SelectionContext, 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    tcx.debug_assert_fully_normalized(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_span::macros::bug_impl(None,
    format_args!("Encountered error `{0:?}` selecting `{1:?}` during codegen",
        e, trait_ref), Location::caller())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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_traits/src/codegen.rs:49",
                        "rustc_traits::codegen", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/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(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("selection")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("selection");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&selection)
                                            as &dyn ::tracing::field::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_with_diagnostics(&infcx);
55    let impl_source = selection.map(|obligation| {
56        ocx.register_obligation(obligation);
57    });
58
59    let impl_span = match &impl_source {
60        ImplSource::UserDefined(source) => Some(tcx.def_span(source.impl_def_id)),
61        _ => None,
62    };
63
64    // In principle, we only need to do this so long as `impl_source`
65    // contains unbound type parameters. It could be a slight
66    // optimization to stop iterating early.
67    let errors = ocx.evaluate_obligations_error_on_ambiguity();
68    if !errors.no_errors() {
69        // `rustc_monomorphize::collector` assumes there are no type errors.
70        // Report post-monomorphization overflows here so that `Instance::expect_resolve` doesn't ICE later.
71        for mut err in errors {
72            match err.code {
73                FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
74                    if err.obligation.cause.span.is_dummy() {
75                        if let Some(span) = impl_span {
76                            err.obligation.cause.span = span;
77                        }
78                    }
79
80                    infcx
81                        .err_ctxt()
82                        .report_overflow_obligation(&err.obligation, suggest_increasing_limit);
83                }
84                FulfillmentErrorCode::Cycle(cycle) => {
85                    infcx.err_ctxt().report_overflow_obligation_cycle(&cycle);
86                }
87                _ => {}
88            }
89        }
90        return Err(CodegenObligationError::Unimplemented);
91    }
92
93    let impl_source = infcx.deeply_resolve_ignoring_regions(impl_source);
94    let impl_source = tcx.erase_and_anonymize_regions(impl_source);
95    if impl_source.has_non_region_infer() {
96        // Unused generic types or consts on an impl get replaced with inference vars,
97        // but never resolved, causing the return value of a query to contain inference
98        // vars. We do not have a concept for this and will in fact ICE in stable hashing
99        // of the return value. So bail out instead.
100        let guar = match impl_source {
101            ImplSource::UserDefined(impl_) => tcx.dcx().span_delayed_bug(
102                tcx.def_span(impl_.impl_def_id),
103                "this impl has unconstrained generic parameters",
104            ),
105            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
106        };
107        return Err(CodegenObligationError::UnconstrainedParam(guar));
108    }
109
110    Ok(&*tcx.arena.alloc(impl_source))
111}