Skip to main content

rustc_infer/infer/canonical/
query_response.rs

1//! This module contains the code to instantiate a "query result", and
2//! in particular to extract out the resulting region obligations and
3//! encode them therein.
4//!
5//! For an overview of what canonicalization is and how it fits into
6//! rustc, check out the [chapter in the rustc dev guide][c].
7//!
8//! [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html
9
10use std::fmt::Debug;
11use std::iter;
12
13use rustc_index::{Idx, IndexVec};
14use rustc_middle::arena::ArenaAllocatable;
15use rustc_middle::infer::canonical::{CanonicalVarKind, QueryRegionConstraint};
16use rustc_middle::ty::{self, BoundVar, GenericArg, GenericArgKind, Ty, TyCtxt, TypeFoldable};
17use rustc_span::bug;
18use tracing::{debug, instrument};
19
20use crate::infer::canonical::instantiate::{CanonicalExt, instantiate_value};
21use crate::infer::canonical::{
22    Canonical, CanonicalQueryResponse, CanonicalVarValues, Certainty, OriginalQueryValues,
23    QueryRegionConstraints, QueryResponse,
24};
25use crate::infer::region_constraints::{ConstraintKind, RegionConstraintData};
26use crate::infer::{
27    DefineOpaqueTypes, InferCtxt, InferOk, InferResult, OpaqueTypeStorageEntries, SubregionOrigin,
28    TypeOutlivesConstraint,
29};
30use crate::traits::query::NoSolution;
31use crate::traits::{
32    ObligationCause, PredicateObligations, ScrubbedTraitError, TraitEngine, TraitErrors,
33};
34
35impl<'tcx> InferCtxt<'tcx> {
36    /// This method is meant to be invoked as the final step of a canonical query
37    /// implementation. It is given:
38    ///
39    /// - the instantiated variables `inference_vars` created from the query key
40    /// - the result `answer` of the query
41    /// - a fulfillment context `fulfill_cx` that may contain various obligations which
42    ///   have yet to be proven.
43    ///
44    /// Given this, the function will process the obligations pending
45    /// in `fulfill_cx`:
46    ///
47    /// - If all the obligations can be proven successfully, it will
48    ///   package up any resulting region obligations (extracted from
49    ///   `infcx`) along with the fully resolved value `answer` into a
50    ///   query result (which is then itself canonicalized).
51    /// - If some obligations can be neither proven nor disproven, then
52    ///   the same thing happens, but the resulting query is marked as ambiguous.
53    /// - Finally, if any of the obligations result in a hard error,
54    ///   then `Err(NoSolution)` is returned.
55    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("make_canonicalized_query_response",
                                    "rustc_infer::infer::canonical::query_response",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                                    ::tracing_core::__macro_support::Option::Some(55u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::canonical::query_response"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<CanonicalQueryResponse<'tcx, T>, NoSolution> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let query_response =
                self.make_query_response(inference_vars, answer, fulfill_cx)?;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs:67",
                                    "rustc_infer::infer::canonical::query_response",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                                    ::tracing_core::__macro_support::Option::Some(67u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::canonical::query_response"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::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(&format_args!("query_response = {0:#?}",
                                                                query_response) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let canonical_result = self.canonicalize_response(query_response);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs:69",
                                    "rustc_infer::infer::canonical::query_response",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                                    ::tracing_core::__macro_support::Option::Some(69u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::canonical::query_response"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::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(&format_args!("canonical_result = {0:#?}",
                                                                canonical_result) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            Ok(self.tcx.arena.alloc(canonical_result))
        }
    }
}#[instrument(skip(self, inference_vars, answer, fulfill_cx), level = "trace")]
56    pub fn make_canonicalized_query_response<T>(
57        &self,
58        inference_vars: CanonicalVarValues<'tcx>,
59        answer: T,
60        fulfill_cx: &mut dyn TraitEngine<'tcx, ScrubbedTraitError<'tcx>>,
61    ) -> Result<CanonicalQueryResponse<'tcx, T>, NoSolution>
62    where
63        T: Debug + TypeFoldable<TyCtxt<'tcx>>,
64        Canonical<'tcx, QueryResponse<'tcx, T>>: ArenaAllocatable<'tcx>,
65    {
66        let query_response = self.make_query_response(inference_vars, answer, fulfill_cx)?;
67        debug!("query_response = {:#?}", query_response);
68        let canonical_result = self.canonicalize_response(query_response);
69        debug!("canonical_result = {:#?}", canonical_result);
70
71        Ok(self.tcx.arena.alloc(canonical_result))
72    }
73
74    /// A version of `make_canonicalized_query_response` that does
75    /// not pack in obligations, for contexts that want to drop
76    /// pending obligations instead of treating them as an ambiguity (e.g.
77    /// typeck "probing" contexts).
78    ///
79    /// If you DO want to keep track of pending obligations (which
80    /// include all region obligations, so this includes all cases
81    /// that care about regions) with this function, you have to
82    /// do it yourself, by e.g., having them be a part of the answer.
83    pub fn make_query_response_ignoring_pending_obligations<T>(
84        &self,
85        inference_vars: CanonicalVarValues<'tcx>,
86        answer: T,
87        prev_entries: OpaqueTypeStorageEntries,
88    ) -> Canonical<'tcx, QueryResponse<'tcx, T>>
89    where
90        T: Debug + TypeFoldable<TyCtxt<'tcx>>,
91    {
92        // While we ignore region constraints and pending obligations,
93        // we do return constrained opaque types to avoid unconstrained
94        // inference variables in the response. This is important as we want
95        // to check that opaques in deref steps stay unconstrained.
96        //
97        // This doesn't handle the more general case for non-opaques as
98        // ambiguous `Projection` obligations have same the issue.
99        let opaque_types = if self.next_trait_solver() {
100            self.inner
101                .borrow_mut()
102                .opaque_type_storage
103                .opaque_types_added_since(prev_entries)
104                .map(|(k, v)| (k, v.ty))
105                .collect()
106        } else {
107            ::alloc::vec::Vec::new()vec![]
108        };
109
110        self.canonicalize_response(QueryResponse {
111            var_values: inference_vars.var_values,
112            region_constraints: QueryRegionConstraints::default(),
113            certainty: Certainty::Proven, // Ambiguities are OK!
114            opaque_types,
115            value: answer,
116        })
117    }
118
119    /// Helper for `make_canonicalized_query_response` that does
120    /// everything up until the final canonicalization.
121    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("make_query_response",
                                    "rustc_infer::infer::canonical::query_response",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                                    ::tracing_core::__macro_support::Option::Some(121u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::canonical::query_response"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("inference_vars")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("inference_vars");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("answer")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("answer");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&inference_vars)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&answer)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<QueryResponse<'tcx, T>, NoSolution> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let errors =
                fulfill_cx.evaluate_obligations_error_on_ambiguity(self);
            let certainty =
                match errors {
                    TraitErrors::HasErrors(errors) => {
                        if errors.iter().any(|e| e.is_true_error()) {
                            return Err(NoSolution);
                        } else { Certainty::Ambiguous }
                    }
                    TraitErrors::NoErrors => Certainty::Proven,
                };
            let type_outlives_constraints =
                self.take_registered_type_outlives_constraints();
            let region_assumptions =
                self.take_registered_region_assumptions();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs:148",
                                    "rustc_infer::infer::canonical::query_response",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                                    ::tracing_core::__macro_support::Option::Some(148u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::canonical::query_response"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("type_outlives_constraints")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("type_outlives_constraints");
                                                        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(&type_outlives_constraints)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let region_constraints =
                self.with_region_constraints(|region_constraints|
                        {
                            make_query_region_constraints(type_outlives_constraints,
                                region_constraints, region_assumptions)
                        });
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs:156",
                                    "rustc_infer::infer::canonical::query_response",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                                    ::tracing_core::__macro_support::Option::Some(156u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::canonical::query_response"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("region_constraints")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("region_constraints");
                                                        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(&region_constraints)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let opaque_types =
                self.inner.borrow_mut().opaque_type_storage.take_opaque_types().map(|(k,
                                v)| (k, v.ty)).collect();
            Ok(QueryResponse {
                    var_values: inference_vars.var_values,
                    region_constraints,
                    certainty,
                    value: answer,
                    opaque_types,
                })
        }
    }
}#[instrument(skip(self, fulfill_cx), level = "debug")]
122    fn make_query_response<T>(
123        &self,
124        inference_vars: CanonicalVarValues<'tcx>,
125        answer: T,
126        fulfill_cx: &mut dyn TraitEngine<'tcx, ScrubbedTraitError<'tcx>>,
127    ) -> Result<QueryResponse<'tcx, T>, NoSolution>
128    where
129        T: Debug + TypeFoldable<TyCtxt<'tcx>>,
130    {
131        // Select everything, returning errors.
132        let errors = fulfill_cx.evaluate_obligations_error_on_ambiguity(self);
133
134        let certainty = match errors {
135            TraitErrors::HasErrors(errors) => {
136                if errors.iter().any(|e| e.is_true_error()) {
137                    // True error!
138                    return Err(NoSolution);
139                } else {
140                    Certainty::Ambiguous
141                }
142            }
143            TraitErrors::NoErrors => Certainty::Proven,
144        };
145
146        let type_outlives_constraints = self.take_registered_type_outlives_constraints();
147        let region_assumptions = self.take_registered_region_assumptions();
148        debug!(?type_outlives_constraints);
149        let region_constraints = self.with_region_constraints(|region_constraints| {
150            make_query_region_constraints(
151                type_outlives_constraints,
152                region_constraints,
153                region_assumptions,
154            )
155        });
156        debug!(?region_constraints);
157
158        let opaque_types = self
159            .inner
160            .borrow_mut()
161            .opaque_type_storage
162            .take_opaque_types()
163            .map(|(k, v)| (k, v.ty))
164            .collect();
165
166        Ok(QueryResponse {
167            var_values: inference_vars.var_values,
168            region_constraints,
169            certainty,
170            value: answer,
171            opaque_types,
172        })
173    }
174
175    /// Given the (canonicalized) result to a canonical query,
176    /// instantiates the result so it can be used, plugging in the
177    /// values from the canonical query. (Note that the result may
178    /// have been ambiguous; you should check the certainty level of
179    /// the query before applying this function.)
180    ///
181    /// To get a good understanding of what is happening here, check
182    /// out the [chapter in the rustc dev guide][c].
183    ///
184    /// [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html#processing-the-canonicalized-query-result
185    pub fn instantiate_query_response_and_region_obligations<R>(
186        &self,
187        cause: &ObligationCause<'tcx>,
188        param_env: ty::ParamEnv<'tcx>,
189        original_values: &OriginalQueryValues<'tcx>,
190        query_response: &Canonical<'tcx, QueryResponse<'tcx, R>>,
191    ) -> InferResult<'tcx, R>
192    where
193        R: Debug + TypeFoldable<TyCtxt<'tcx>>,
194    {
195        let InferOk { value: result_args, obligations } =
196            self.query_response_instantiation(cause, param_env, original_values, query_response)?;
197
198        for QueryRegionConstraint { constraint, visible_for_leak_check: vis, .. } in
199            &query_response.value.region_constraints.constraints
200        {
201            let constraint = instantiate_value(self.tcx, &result_args, *constraint);
202            match constraint {
203                ty::RegionConstraint::Outlives(clause) => {
204                    self.register_outlives_constraint(clause, *vis, cause);
205                }
206                ty::RegionConstraint::Eq(clause) => {
207                    self.register_region_eq_constraint(clause, *vis, cause);
208                }
209            }
210        }
211
212        for assumption in &query_response.value.region_constraints.assumptions {
213            let assumption = instantiate_value(self.tcx, &result_args, *assumption);
214            self.register_region_assumption(assumption);
215        }
216
217        let user_result: R =
218            query_response.instantiate_projected(self.tcx, &result_args, |q_r| q_r.value.clone());
219
220        Ok(InferOk { value: user_result, obligations })
221    }
222
223    /// An alternative to
224    /// `instantiate_query_response_and_region_obligations` that is more
225    /// efficient for NLL. NLL is a bit more advanced in the
226    /// "transition to chalk" than the rest of the compiler. During
227    /// the NLL type check, all of the "processing" of types and
228    /// things happens in queries -- the NLL checker itself is only
229    /// interested in the region obligations (`'a: 'b` or `T: 'b`)
230    /// that come out of these queries, which it wants to convert into
231    /// MIR-based constraints and solve. Therefore, it is most
232    /// convenient for the NLL Type Checker to **directly consume**
233    /// the `QueryOutlivesConstraint` values that arise from doing a
234    /// query. This is contrast to other parts of the compiler, which
235    /// would prefer for those `QueryOutlivesConstraint` to be converted
236    /// into the older infcx-style constraints (e.g., calls to
237    /// `sub_regions` or `register_region_obligation`).
238    ///
239    /// Therefore, `instantiate_nll_query_response_and_region_obligations` performs the same
240    /// basic operations as `instantiate_query_response_and_region_obligations` but
241    /// it returns its result differently:
242    ///
243    /// - It creates an instantiation `S` that maps from the original
244    ///   query variables to the values computed in the query
245    ///   result. If any errors arise, they are propagated back as an
246    ///   `Err` result.
247    /// - In the case of a successful instantiation, we will append
248    ///   `QueryOutlivesConstraint` values onto the
249    ///   `output_query_region_constraints` vector for the solver to
250    ///   use (if an error arises, some values may also be pushed, but
251    ///   they should be ignored).
252    /// - It **can happen** (though it rarely does currently) that
253    ///   equating types and things will give rise to subobligations
254    ///   that must be processed. In this case, those subobligations
255    ///   are propagated back in the return value.
256    /// - Finally, the query result (of type `R`) is propagated back,
257    ///   after applying the instantiation `S`.
258    pub fn instantiate_nll_query_response_and_region_obligations<R>(
259        &self,
260        cause: &ObligationCause<'tcx>,
261        param_env: ty::ParamEnv<'tcx>,
262        original_values: &OriginalQueryValues<'tcx>,
263        query_response: &Canonical<'tcx, QueryResponse<'tcx, R>>,
264        output_query_region_constraints: &mut QueryRegionConstraints<'tcx>,
265    ) -> InferResult<'tcx, (R, Certainty)>
266    where
267        R: Debug + TypeFoldable<TyCtxt<'tcx>>,
268    {
269        let InferOk { value: result_args, mut obligations } = self
270            .query_response_instantiation_guess(
271                cause,
272                param_env,
273                original_values,
274                query_response,
275            )?;
276
277        // Compute `QueryOutlivesConstraint` values that unify each of
278        // the original values `v_o` that was canonicalized into a
279        // variable...
280
281        let constraint_category = cause.to_constraint_category();
282
283        for (index, original_value) in original_values.var_values.iter().enumerate() {
284            // ...with the value `v_r` of that variable from the query.
285            let result_value = query_response
286                .instantiate_projected(self.tcx, &result_args, |v| v.var_values[index]);
287            match (original_value.kind(), result_value.kind()) {
288                (GenericArgKind::Lifetime(re1), GenericArgKind::Lifetime(re2))
289                    if re1.is_erased() && re2.is_erased() =>
290                {
291                    // No action needed.
292                }
293
294                (GenericArgKind::Lifetime(v_o), GenericArgKind::Lifetime(v_r)) => {
295                    if v_o != v_r {
296                        let constraint = QueryRegionConstraint {
297                            constraint: ty::RegionEqPredicate(v_o, v_r).into(),
298                            category: constraint_category,
299                            visible_for_leak_check: ty::VisibleForLeakCheck::Yes,
300                        };
301                        output_query_region_constraints.constraints.push(constraint);
302                    }
303                }
304
305                (GenericArgKind::Type(v1), GenericArgKind::Type(v2)) => {
306                    obligations.extend(
307                        self.eq_raw(&cause, param_env, DefineOpaqueTypes::Yes, v1, v2)?
308                            .into_obligations(),
309                    );
310                }
311
312                (GenericArgKind::Const(v1), GenericArgKind::Const(v2)) => {
313                    obligations.extend(
314                        self.eq_raw(&cause, param_env, DefineOpaqueTypes::Yes, v1, v2)?
315                            .into_obligations(),
316                    );
317                }
318
319                _ => {
320                    ::rustc_span::macros::bug_impl(None,
    format_args!("kind mismatch, cannot unify {0:?} and {1:?}",
        original_value, result_value), Location::caller());bug!("kind mismatch, cannot unify {:?} and {:?}", original_value, result_value);
321                }
322            }
323        }
324
325        let QueryResponse {
326            var_values: _,
327            ref region_constraints,
328            certainty,
329            opaque_types: _,
330            ref value,
331        } = query_response.value;
332
333        // ...also include the other query region constraints from the query.
334        output_query_region_constraints.constraints.extend(
335            region_constraints.constraints.iter().filter_map(|&r_c| {
336                let r_c = instantiate_value(self.tcx, &result_args, r_c);
337
338                // Screen out `'a: 'a` or `'a == 'a` cases.
339                if r_c.constraint.is_trivial() { None } else { Some(r_c) }
340            }),
341        );
342
343        // FIXME(higher_ranked_auto): Optimize this to instantiate all assumptions
344        // at once, rather than calling `instantiate_value` repeatedly which may
345        // create more universes.
346        output_query_region_constraints.assumptions.extend(
347            region_constraints
348                .assumptions
349                .iter()
350                .map(|&r_c| instantiate_value(self.tcx, &result_args, r_c)),
351        );
352
353        let user_result: R = instantiate_value(self.tcx, &result_args, value.clone());
354
355        Ok(InferOk { value: (user_result, certainty), obligations })
356    }
357
358    /// Given the original values and the (canonicalized) result from
359    /// computing a query, returns an instantiation that can be applied
360    /// to the query result to convert the result back into the
361    /// original namespace.
362    ///
363    /// The instantiation also comes accompanied with subobligations
364    /// that arose from unification; these might occur if (for
365    /// example) we are doing lazy normalization and the value
366    /// assigned to a type variable is unified with an unnormalized
367    /// projection.
368    fn query_response_instantiation<R>(
369        &self,
370        cause: &ObligationCause<'tcx>,
371        param_env: ty::ParamEnv<'tcx>,
372        original_values: &OriginalQueryValues<'tcx>,
373        query_response: &Canonical<'tcx, QueryResponse<'tcx, R>>,
374    ) -> InferResult<'tcx, CanonicalVarValues<'tcx>>
375    where
376        R: Debug + TypeFoldable<TyCtxt<'tcx>>,
377    {
378        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs:378",
                        "rustc_infer::infer::canonical::query_response",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                        ::tracing_core::__macro_support::Option::Some(378u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::canonical::query_response"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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(&format_args!("query_response_instantiation(original_values={0:#?}, query_response={1:#?})",
                                                    original_values, query_response) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
379            "query_response_instantiation(original_values={:#?}, query_response={:#?})",
380            original_values, query_response,
381        );
382
383        let mut value = self.query_response_instantiation_guess(
384            cause,
385            param_env,
386            original_values,
387            query_response,
388        )?;
389
390        value.obligations.extend(
391            self.unify_query_response_instantiation_guess(
392                cause,
393                param_env,
394                original_values,
395                &value.value,
396                query_response,
397            )?
398            .into_obligations(),
399        );
400
401        Ok(value)
402    }
403
404    /// Given the original values and the (canonicalized) result from
405    /// computing a query, returns a **guess** at an instantiation that
406    /// can be applied to the query result to convert the result back
407    /// into the original namespace. This is called a **guess**
408    /// because it uses a quick heuristic to find the values for each
409    /// canonical variable; if that quick heuristic fails, then we
410    /// will instantiate fresh inference variables for each canonical
411    /// variable instead. Therefore, the result of this method must be
412    /// properly unified
413    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("query_response_instantiation_guess",
                                    "rustc_infer::infer::canonical::query_response",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                                    ::tracing_core::__macro_support::Option::Some(413u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::canonical::query_response"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cause");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("original_values")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("original_values");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("query_response")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("query_response");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&original_values)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&query_response)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    InferResult<'tcx, CanonicalVarValues<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut universe_map = original_values.universe_map.clone();
            let num_universes_in_query = original_values.universe_map.len();
            let num_universes_in_response =
                query_response.max_universe.as_usize() + 1;
            for _ in num_universes_in_query..num_universes_in_response {
                universe_map.push(self.create_next_universe());
            }
            if !!universe_map.is_empty() {
                ::core::panicking::panic("assertion failed: !universe_map.is_empty()")
            };
            {
                match (&universe_map[ty::UniverseIndex::ROOT.as_usize()],
                        &ty::UniverseIndex::ROOT) {
                    (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);
                        }
                    }
                }
            };
            let result_values = query_response.value.var_values;
            {
                match (&original_values.var_values.len(),
                        &result_values.len()) {
                    (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);
                        }
                    }
                }
            };
            let mut opt_values: IndexVec<BoundVar, Option<GenericArg<'tcx>>> =
                IndexVec::from_elem_n(None, query_response.var_kinds.len());
            for (original_value, result_value) in
                iter::zip(&original_values.var_values, result_values) {
                match result_value.kind() {
                    GenericArgKind::Type(result_value) => {
                        if let ty::Bound(index_kind, b) = *result_value.kind() &&
                                !#[allow(non_exhaustive_omitted_patterns)] match query_response.var_kinds[b.var.as_usize()]
                                        {
                                        CanonicalVarKind::Ty { .. } => true,
                                        _ => false,
                                    } {
                            if !#[allow(non_exhaustive_omitted_patterns)] match index_kind
                                        {
                                        ty::BoundVarIndexKind::Canonical => true,
                                        _ => false,
                                    } {
                                ::core::panicking::panic("assertion failed: matches!(index_kind, ty::BoundVarIndexKind::Canonical)")
                            };
                            opt_values[b.var] = Some(*original_value);
                        }
                    }
                    GenericArgKind::Lifetime(result_value) => {
                        if let ty::ReBound(index_kind, b) = result_value.kind() {
                            if !#[allow(non_exhaustive_omitted_patterns)] match index_kind
                                        {
                                        ty::BoundVarIndexKind::Canonical => true,
                                        _ => false,
                                    } {
                                ::core::panicking::panic("assertion failed: matches!(index_kind, ty::BoundVarIndexKind::Canonical)")
                            };
                            opt_values[b.var] = Some(*original_value);
                        }
                    }
                    GenericArgKind::Const(result_value) => {
                        if let ty::ConstKind::Bound(index_kind, b) =
                                result_value.kind() {
                            if !#[allow(non_exhaustive_omitted_patterns)] match index_kind
                                        {
                                        ty::BoundVarIndexKind::Canonical => true,
                                        _ => false,
                                    } {
                                ::core::panicking::panic("assertion failed: matches!(index_kind, ty::BoundVarIndexKind::Canonical)")
                            };
                            opt_values[b.var] = Some(*original_value);
                        }
                    }
                }
            }
            let tcx = self.tcx;
            let var_kinds = query_response.var_kinds;
            let var_values =
                CanonicalVarValues::instantiate(tcx, var_kinds,
                    |prev_var_values, kind|
                        {
                            if kind.universe() != ty::UniverseIndex::ROOT {
                                self.instantiate_canonical_var(cause.span, kind,
                                    &prev_var_values, |u| { universe_map[u.as_usize()] })
                            } else if kind.is_existential() {
                                match opt_values[BoundVar::new(prev_var_values.len())] {
                                    Some(k) => k,
                                    None =>
                                        self.instantiate_canonical_var(cause.span, kind,
                                            &prev_var_values, |u| universe_map[u.as_usize()]),
                                }
                            } else {
                                opt_values[BoundVar::new(prev_var_values.len())].expect("expected placeholder to be unified with itself during response")
                            }
                        });
            let mut obligations = PredicateObligations::new();
            for &(a, b) in &query_response.value.opaque_types {
                let a = instantiate_value(self.tcx, &var_values, a);
                let b = instantiate_value(self.tcx, &var_values, b);
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs:526",
                                        "rustc_infer::infer::canonical::query_response",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                                        ::tracing_core::__macro_support::Option::Some(526u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::canonical::query_response"),
                                        ::tracing_core::field::FieldSet::new(&["message",
                                                        {
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("a")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("a");
                                                            NAME.as_str()
                                                        },
                                                        {
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("b")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("b");
                                                            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(&format_args!("constrain opaque type")
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                obligations.extend(self.eq_raw(cause, param_env,
                                DefineOpaqueTypes::Yes,
                                Ty::new_opaque(self.tcx, ty::IsRigid::No,
                                    a.def_id.to_def_id(), a.args), b)?.obligations);
            }
            Ok(InferOk { value: var_values, obligations })
        }
    }
}#[instrument(level = "debug", skip(self, param_env))]
414    fn query_response_instantiation_guess<R>(
415        &self,
416        cause: &ObligationCause<'tcx>,
417        param_env: ty::ParamEnv<'tcx>,
418        original_values: &OriginalQueryValues<'tcx>,
419        query_response: &Canonical<'tcx, QueryResponse<'tcx, R>>,
420    ) -> InferResult<'tcx, CanonicalVarValues<'tcx>>
421    where
422        R: Debug + TypeFoldable<TyCtxt<'tcx>>,
423    {
424        // For each new universe created in the query result that did
425        // not appear in the original query, create a local
426        // superuniverse.
427        let mut universe_map = original_values.universe_map.clone();
428        let num_universes_in_query = original_values.universe_map.len();
429        let num_universes_in_response = query_response.max_universe.as_usize() + 1;
430        for _ in num_universes_in_query..num_universes_in_response {
431            universe_map.push(self.create_next_universe());
432        }
433        assert!(!universe_map.is_empty()); // always have the root universe
434        assert_eq!(universe_map[ty::UniverseIndex::ROOT.as_usize()], ty::UniverseIndex::ROOT);
435
436        // Every canonical query result includes values for each of
437        // the inputs to the query. Therefore, we begin by unifying
438        // these values with the original inputs that were
439        // canonicalized.
440        let result_values = query_response.value.var_values;
441        assert_eq!(original_values.var_values.len(), result_values.len());
442
443        // Quickly try to find initial values for the canonical
444        // variables in the result in terms of the query. We do this
445        // by iterating down the values that the query gave to each of
446        // the canonical inputs. If we find that one of those values
447        // is directly equal to one of the canonical variables in the
448        // result, then we can type the corresponding value from the
449        // input. See the example above.
450        let mut opt_values: IndexVec<BoundVar, Option<GenericArg<'tcx>>> =
451            IndexVec::from_elem_n(None, query_response.var_kinds.len());
452
453        for (original_value, result_value) in iter::zip(&original_values.var_values, result_values)
454        {
455            match result_value.kind() {
456                GenericArgKind::Type(result_value) => {
457                    // We disable the instantiation guess for inference variables
458                    // and only use it for placeholders. We need to handle the
459                    // `sub_root` of type inference variables which would make this
460                    // more involved. They are also a lot rarer than region variables.
461                    if let ty::Bound(index_kind, b) = *result_value.kind()
462                        && !matches!(
463                            query_response.var_kinds[b.var.as_usize()],
464                            CanonicalVarKind::Ty { .. }
465                        )
466                    {
467                        // We only allow a `Canonical` index in generic parameters.
468                        assert!(matches!(index_kind, ty::BoundVarIndexKind::Canonical));
469                        opt_values[b.var] = Some(*original_value);
470                    }
471                }
472                GenericArgKind::Lifetime(result_value) => {
473                    if let ty::ReBound(index_kind, b) = result_value.kind() {
474                        // We only allow a `Canonical` index in generic parameters.
475                        assert!(matches!(index_kind, ty::BoundVarIndexKind::Canonical));
476                        opt_values[b.var] = Some(*original_value);
477                    }
478                }
479                GenericArgKind::Const(result_value) => {
480                    if let ty::ConstKind::Bound(index_kind, b) = result_value.kind() {
481                        // We only allow a `Canonical` index in generic parameters.
482                        assert!(matches!(index_kind, ty::BoundVarIndexKind::Canonical));
483                        opt_values[b.var] = Some(*original_value);
484                    }
485                }
486            }
487        }
488
489        // Create result arguments: if we found a value for a
490        // given variable in the loop above, use that. Otherwise, use
491        // a fresh inference variable.
492        let tcx = self.tcx;
493        let var_kinds = query_response.var_kinds;
494        let var_values =
495            CanonicalVarValues::instantiate(tcx, var_kinds, |prev_var_values, kind| {
496                if kind.universe() != ty::UniverseIndex::ROOT {
497                    // A variable from inside a binder of the query. While ideally these shouldn't
498                    // exist at all, we have to deal with them for now.
499                    self.instantiate_canonical_var(cause.span, kind, &prev_var_values, |u| {
500                        universe_map[u.as_usize()]
501                    })
502                } else if kind.is_existential() {
503                    match opt_values[BoundVar::new(prev_var_values.len())] {
504                        Some(k) => k,
505                        None => self.instantiate_canonical_var(
506                            cause.span,
507                            kind,
508                            &prev_var_values,
509                            |u| universe_map[u.as_usize()],
510                        ),
511                    }
512                } else {
513                    // For placeholders which were already part of the input, we simply map this
514                    // universal bound variable back the placeholder of the input.
515                    opt_values[BoundVar::new(prev_var_values.len())]
516                        .expect("expected placeholder to be unified with itself during response")
517                }
518            });
519
520        let mut obligations = PredicateObligations::new();
521
522        // Carry all newly resolved opaque types to the caller's scope
523        for &(a, b) in &query_response.value.opaque_types {
524            let a = instantiate_value(self.tcx, &var_values, a);
525            let b = instantiate_value(self.tcx, &var_values, b);
526            debug!(?a, ?b, "constrain opaque type");
527            // We use equate here instead of, for example, just registering the
528            // opaque type's hidden value directly, because the hidden type may have been an inference
529            // variable that got constrained to the opaque type itself. In that case we want to equate
530            // the generic args of the opaque with the generic params of its hidden type version.
531            obligations.extend(
532                self.eq_raw(
533                    cause,
534                    param_env,
535                    DefineOpaqueTypes::Yes,
536                    Ty::new_opaque(self.tcx, ty::IsRigid::No, a.def_id.to_def_id(), a.args),
537                    b,
538                )?
539                .obligations,
540            );
541        }
542
543        Ok(InferOk { value: var_values, obligations })
544    }
545
546    /// Given a "guess" at the values for the canonical variables in
547    /// the input, try to unify with the *actual* values found in the
548    /// query result. Often, but not always, this is a no-op, because
549    /// we already found the mapping in the "guessing" step.
550    ///
551    /// See also: [`Self::query_response_instantiation_guess`]
552    fn unify_query_response_instantiation_guess<R>(
553        &self,
554        cause: &ObligationCause<'tcx>,
555        param_env: ty::ParamEnv<'tcx>,
556        original_values: &OriginalQueryValues<'tcx>,
557        result_args: &CanonicalVarValues<'tcx>,
558        query_response: &Canonical<'tcx, QueryResponse<'tcx, R>>,
559    ) -> InferResult<'tcx, ()>
560    where
561        R: Debug + TypeFoldable<TyCtxt<'tcx>>,
562    {
563        // A closure that yields the result value for the given
564        // canonical variable; this is taken from
565        // `query_response.var_values` after applying the instantiation
566        // by `result_args`.
567        let instantiated_query_response = |index: usize| -> GenericArg<'tcx> {
568            query_response.instantiate_projected(self.tcx, result_args, |v| v.var_values[index])
569        };
570
571        // Unify the original value for each variable with the value
572        // taken from `query_response` (after applying `result_args`).
573        self.unify_canonical_vars(cause, param_env, original_values, instantiated_query_response)
574    }
575
576    /// Given two sets of values for the same set of canonical variables, unify them.
577    /// The second set is produced lazily by supplying indices from the first set.
578    fn unify_canonical_vars(
579        &self,
580        cause: &ObligationCause<'tcx>,
581        param_env: ty::ParamEnv<'tcx>,
582        variables1: &OriginalQueryValues<'tcx>,
583        variables2: impl Fn(usize) -> GenericArg<'tcx>,
584    ) -> InferResult<'tcx, ()> {
585        let mut obligations = PredicateObligations::new();
586        for (index, value1) in variables1.var_values.iter().enumerate() {
587            let value2 = variables2(index);
588
589            match (value1.kind(), value2.kind()) {
590                (GenericArgKind::Type(v1), GenericArgKind::Type(v2)) => {
591                    obligations.extend(
592                        self.eq_raw(cause, param_env, DefineOpaqueTypes::Yes, v1, v2)?
593                            .into_obligations(),
594                    );
595                }
596                (GenericArgKind::Lifetime(re1), GenericArgKind::Lifetime(re2))
597                    if re1.is_erased() && re2.is_erased() =>
598                {
599                    // no action needed
600                }
601                (GenericArgKind::Lifetime(v1), GenericArgKind::Lifetime(v2)) => {
602                    self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(
603                        SubregionOrigin::RelateRegionParamBound(cause.span, None),
604                        v1,
605                        v2,
606                        ty::VisibleForLeakCheck::Yes,
607                    );
608                }
609                (GenericArgKind::Const(v1), GenericArgKind::Const(v2)) => {
610                    let ok = self.eq_raw(cause, param_env, DefineOpaqueTypes::Yes, v1, v2)?;
611                    obligations.extend(ok.into_obligations());
612                }
613                _ => {
614                    ::rustc_span::macros::bug_impl(None,
    format_args!("kind mismatch, cannot unify {0:?} and {1:?}", value1,
        value2), Location::caller());bug!("kind mismatch, cannot unify {:?} and {:?}", value1, value2,);
615                }
616            }
617        }
618        Ok(InferOk { value: (), obligations })
619    }
620}
621
622/// Given the type outlives constraints and region constraints scraped from the infcx,
623/// creates query region constraints.
624pub fn make_query_region_constraints<'tcx>(
625    type_outlives_constraints: Vec<TypeOutlivesConstraint<'tcx>>,
626    region_constraints: &RegionConstraintData<'tcx>,
627    assumptions: Vec<ty::ArgOutlivesClause<'tcx>>,
628) -> QueryRegionConstraints<'tcx> {
629    let RegionConstraintData { constraints, verifys } = region_constraints;
630
631    if !verifys.is_empty() {
    ::core::panicking::panic("assertion failed: verifys.is_empty()")
};assert!(verifys.is_empty());
632
633    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs:633",
                        "rustc_infer::infer::canonical::query_response",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                        ::tracing_core::__macro_support::Option::Some(633u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::canonical::query_response"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("constraints")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("constraints");
                                            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(&constraints)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?constraints);
634
635    let constraints: Vec<QueryRegionConstraint<'tcx>> = constraints
636        .iter()
637        .map(|(c, origin)| match c.kind {
638            ConstraintKind::VarSubVar
639            | ConstraintKind::RegSubVar
640            | ConstraintKind::VarSubReg
641            | ConstraintKind::RegSubReg => {
642                // Swap regions because we are going from sub (<=) to outlives (>=).
643                let constraint = ty::OutlivesClause(c.sup.into(), c.sub).into();
644                QueryRegionConstraint {
645                    constraint,
646                    category: origin.to_constraint_category(),
647                    visible_for_leak_check: c.visible_for_leak_check,
648                }
649            }
650
651            ConstraintKind::VarEqVar | ConstraintKind::VarEqReg | ConstraintKind::RegEqReg => {
652                let constraint = ty::RegionEqPredicate(c.sub, c.sup).into();
653                QueryRegionConstraint {
654                    constraint,
655                    category: origin.to_constraint_category(),
656                    visible_for_leak_check: c.visible_for_leak_check,
657                }
658            }
659        })
660        .chain(type_outlives_constraints.into_iter().map(
661            |TypeOutlivesConstraint { sub_region, sup_type, origin }| {
662                QueryRegionConstraint {
663                    constraint: ty::OutlivesClause(sup_type.into(), sub_region).into(),
664                    category: origin.to_constraint_category(),
665                    // We don't do leak checks for type outlives
666                    visible_for_leak_check: ty::VisibleForLeakCheck::Unreachable,
667                }
668            },
669        ))
670        .collect();
671
672    QueryRegionConstraints { constraints, assumptions }
673}