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::bug;
16use rustc_middle::infer::canonical::{CanonicalVarKind, QueryRegionConstraint};
17use rustc_middle::ty::{self, BoundVar, GenericArg, GenericArgKind, Ty, TyCtxt, TypeFoldable};
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/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/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/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/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/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/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/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/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/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/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,
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/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/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 region_obligations =
                self.take_registered_region_obligations();
            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/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/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/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/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("region_obligations")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("region_obligations");
                                                        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_obligations)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let solver_constraints = self.take_solver_region_constraints();
            let region_constraints =
                self.with_region_constraints(|region_constraints|
                        {
                            make_query_region_constraints(region_obligations,
                                region_constraints, region_assumptions, solver_constraints)
                        });
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/compiler/rustc_infer/src/infer/canonical/query_response.rs:158",
                                    "rustc_infer::infer::canonical::query_response",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                                    ::tracing_core::__macro_support::Option::Some(158u32),
                                    ::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,
                    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 region_obligations = self.take_registered_region_obligations();
147        let region_assumptions = self.take_registered_region_assumptions();
148        debug!(?region_obligations);
149        let solver_constraints = self.take_solver_region_constraints();
150        let region_constraints = self.with_region_constraints(|region_constraints| {
151            make_query_region_constraints(
152                region_obligations,
153                region_constraints,
154                region_assumptions,
155                solver_constraints,
156            )
157        });
158        debug!(?region_constraints);
159
160        let opaque_types = self
161            .inner
162            .borrow_mut()
163            .opaque_type_storage
164            .take_opaque_types()
165            .map(|(k, v)| (k, v.ty))
166            .collect();
167
168        Ok(QueryResponse {
169            var_values: inference_vars,
170            region_constraints,
171            certainty,
172            value: answer,
173            opaque_types,
174        })
175    }
176
177    /// Given the (canonicalized) result to a canonical query,
178    /// instantiates the result so it can be used, plugging in the
179    /// values from the canonical query. (Note that the result may
180    /// have been ambiguous; you should check the certainty level of
181    /// the query before applying this function.)
182    ///
183    /// To get a good understanding of what is happening here, check
184    /// out the [chapter in the rustc dev guide][c].
185    ///
186    /// [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html#processing-the-canonicalized-query-result
187    pub fn instantiate_query_response_and_region_obligations<R>(
188        &self,
189        cause: &ObligationCause<'tcx>,
190        param_env: ty::ParamEnv<'tcx>,
191        original_values: &OriginalQueryValues<'tcx>,
192        query_response: &Canonical<'tcx, QueryResponse<'tcx, R>>,
193    ) -> InferResult<'tcx, R>
194    where
195        R: Debug + TypeFoldable<TyCtxt<'tcx>>,
196    {
197        let InferOk { value: result_args, obligations } =
198            self.query_response_instantiation(cause, param_env, original_values, query_response)?;
199
200        let QueryRegionConstraints { constraints, assumptions, solver_constraints } =
201            &query_response.value.region_constraints;
202
203        for QueryRegionConstraint { constraint, visible_for_leak_check: vis, .. } in constraints {
204            let constraint = instantiate_value(self.tcx, &result_args, *constraint);
205            match constraint {
206                ty::RegionConstraint::Outlives(clause) => {
207                    self.register_outlives_constraint(clause, *vis, cause);
208                }
209                ty::RegionConstraint::Eq(clause) => {
210                    self.register_region_eq_constraint(clause, *vis, cause);
211                }
212            }
213        }
214
215        for assumption in assumptions {
216            let assumption = instantiate_value(self.tcx, &result_args, *assumption);
217            self.register_region_assumption(assumption);
218        }
219
220        let solver_constraints =
221            instantiate_value(self.tcx, &result_args, solver_constraints.clone());
222        self.register_solver_region_constraint(solver_constraints.with_spans(cause.span));
223
224        let user_result: R =
225            query_response.instantiate_projected(self.tcx, &result_args, |q_r| q_r.value.clone());
226
227        Ok(InferOk { value: user_result, obligations })
228    }
229
230    /// An alternative to
231    /// `instantiate_query_response_and_region_obligations` that is more
232    /// efficient for NLL. NLL is a bit more advanced in the
233    /// "transition to chalk" than the rest of the compiler. During
234    /// the NLL type check, all of the "processing" of types and
235    /// things happens in queries -- the NLL checker itself is only
236    /// interested in the region obligations (`'a: 'b` or `T: 'b`)
237    /// that come out of these queries, which it wants to convert into
238    /// MIR-based constraints and solve. Therefore, it is most
239    /// convenient for the NLL Type Checker to **directly consume**
240    /// the `QueryOutlivesConstraint` values that arise from doing a
241    /// query. This is contrast to other parts of the compiler, which
242    /// would prefer for those `QueryOutlivesConstraint` to be converted
243    /// into the older infcx-style constraints (e.g., calls to
244    /// `sub_regions` or `register_region_obligation`).
245    ///
246    /// Therefore, `instantiate_nll_query_response_and_region_obligations` performs the same
247    /// basic operations as `instantiate_query_response_and_region_obligations` but
248    /// it returns its result differently:
249    ///
250    /// - It creates an instantiation `S` that maps from the original
251    ///   query variables to the values computed in the query
252    ///   result. If any errors arise, they are propagated back as an
253    ///   `Err` result.
254    /// - In the case of a successful instantiation, we will append
255    ///   `QueryOutlivesConstraint` values onto the
256    ///   `output_query_region_constraints` vector for the solver to
257    ///   use (if an error arises, some values may also be pushed, but
258    ///   they should be ignored).
259    /// - It **can happen** (though it rarely does currently) that
260    ///   equating types and things will give rise to subobligations
261    ///   that must be processed. In this case, those subobligations
262    ///   are propagated back in the return value.
263    /// - Finally, the query result (of type `R`) is propagated back,
264    ///   after applying the instantiation `S`.
265    pub fn instantiate_nll_query_response_and_region_obligations<R>(
266        &self,
267        cause: &ObligationCause<'tcx>,
268        param_env: ty::ParamEnv<'tcx>,
269        original_values: &OriginalQueryValues<'tcx>,
270        query_response: &Canonical<'tcx, QueryResponse<'tcx, R>>,
271        output_query_region_constraints: &mut QueryRegionConstraints<'tcx>,
272    ) -> InferResult<'tcx, R>
273    where
274        R: Debug + TypeFoldable<TyCtxt<'tcx>>,
275    {
276        let InferOk { value: result_args, mut obligations } = self
277            .query_response_instantiation_guess(
278                cause,
279                param_env,
280                original_values,
281                query_response,
282            )?;
283
284        // Compute `QueryOutlivesConstraint` values that unify each of
285        // the original values `v_o` that was canonicalized into a
286        // variable...
287
288        let constraint_category = cause.to_constraint_category();
289
290        for (index, original_value) in original_values.var_values.iter().enumerate() {
291            // ...with the value `v_r` of that variable from the query.
292            let result_value = query_response.instantiate_projected(self.tcx, &result_args, |v| {
293                v.var_values[BoundVar::new(index)]
294            });
295            match (original_value.kind(), result_value.kind()) {
296                (GenericArgKind::Lifetime(re1), GenericArgKind::Lifetime(re2))
297                    if re1.is_erased() && re2.is_erased() =>
298                {
299                    // No action needed.
300                }
301
302                (GenericArgKind::Lifetime(v_o), GenericArgKind::Lifetime(v_r)) => {
303                    if v_o != v_r {
304                        let constraint = QueryRegionConstraint {
305                            constraint: ty::RegionEqPredicate(v_o, v_r).into(),
306                            category: constraint_category,
307                            visible_for_leak_check: ty::VisibleForLeakCheck::Yes,
308                        };
309                        output_query_region_constraints.constraints.push(constraint);
310                    }
311                }
312
313                (GenericArgKind::Type(v1), GenericArgKind::Type(v2)) => {
314                    obligations.extend(
315                        self.at(&cause, param_env)
316                            .eq(DefineOpaqueTypes::Yes, v1, v2)?
317                            .into_obligations(),
318                    );
319                }
320
321                (GenericArgKind::Const(v1), GenericArgKind::Const(v2)) => {
322                    obligations.extend(
323                        self.at(&cause, param_env)
324                            .eq(DefineOpaqueTypes::Yes, v1, v2)?
325                            .into_obligations(),
326                    );
327                }
328
329                _ => {
330                    ::rustc_middle::util::bug::bug_fmt(format_args!("kind mismatch, cannot unify {0:?} and {1:?}",
        original_value, result_value));bug!("kind mismatch, cannot unify {:?} and {:?}", original_value, result_value);
331                }
332            }
333        }
334
335        let QueryRegionConstraints { constraints, assumptions, solver_constraints } =
336            &query_response.value.region_constraints;
337
338        // ...also include the other query region constraints from the query.
339        output_query_region_constraints.constraints.extend(constraints.iter().filter_map(|&r_c| {
340            let r_c = instantiate_value(self.tcx, &result_args, r_c);
341
342            // Screen out `'a: 'a` or `'a == 'a` cases.
343            if r_c.constraint.is_trivial() { None } else { Some(r_c) }
344        }));
345
346        // FIXME(higher_ranked_auto): Optimize this to instantiate all assumptions
347        // at once, rather than calling `instantiate_value` repeatedly which may
348        // create more universes.
349        output_query_region_constraints
350            .assumptions
351            .extend(assumptions.iter().map(|&r_c| instantiate_value(self.tcx, &result_args, r_c)));
352
353        let solver_constraints =
354            instantiate_value(self.tcx, &result_args, solver_constraints.clone());
355        output_query_region_constraints.solver_constraints =
356            ty::region_constraint::RegionConstraint::build_and(
357                std::mem::take(&mut output_query_region_constraints.solver_constraints),
358                solver_constraints,
359            );
360
361        let user_result: R =
362            query_response.instantiate_projected(self.tcx, &result_args, |q_r| q_r.value.clone());
363
364        Ok(InferOk { value: user_result, obligations })
365    }
366
367    /// Given the original values and the (canonicalized) result from
368    /// computing a query, returns an instantiation that can be applied
369    /// to the query result to convert the result back into the
370    /// original namespace.
371    ///
372    /// The instantiation also comes accompanied with subobligations
373    /// that arose from unification; these might occur if (for
374    /// example) we are doing lazy normalization and the value
375    /// assigned to a type variable is unified with an unnormalized
376    /// projection.
377    fn query_response_instantiation<R>(
378        &self,
379        cause: &ObligationCause<'tcx>,
380        param_env: ty::ParamEnv<'tcx>,
381        original_values: &OriginalQueryValues<'tcx>,
382        query_response: &Canonical<'tcx, QueryResponse<'tcx, R>>,
383    ) -> InferResult<'tcx, CanonicalVarValues<'tcx>>
384    where
385        R: Debug + TypeFoldable<TyCtxt<'tcx>>,
386    {
387        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/compiler/rustc_infer/src/infer/canonical/query_response.rs:387",
                        "rustc_infer::infer::canonical::query_response",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                        ::tracing_core::__macro_support::Option::Some(387u32),
                        ::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!(
388            "query_response_instantiation(original_values={:#?}, query_response={:#?})",
389            original_values, query_response,
390        );
391
392        let mut value = self.query_response_instantiation_guess(
393            cause,
394            param_env,
395            original_values,
396            query_response,
397        )?;
398
399        value.obligations.extend(
400            self.unify_query_response_instantiation_guess(
401                cause,
402                param_env,
403                original_values,
404                &value.value,
405                query_response,
406            )?
407            .into_obligations(),
408        );
409
410        Ok(value)
411    }
412
413    /// Given the original values and the (canonicalized) result from
414    /// computing a query, returns a **guess** at an instantiation that
415    /// can be applied to the query result to convert the result back
416    /// into the original namespace. This is called a **guess**
417    /// because it uses a quick heuristic to find the values for each
418    /// canonical variable; if that quick heuristic fails, then we
419    /// will instantiate fresh inference variables for each canonical
420    /// variable instead. Therefore, the result of this method must be
421    /// properly unified
422    {}
#[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/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                                    ::tracing_core::__macro_support::Option::Some(422u32),
                                    ::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,
                    |var_values, kind|
                        {
                            if kind.universe() != ty::UniverseIndex::ROOT {
                                self.instantiate_canonical_var(cause.span, kind,
                                    &var_values, |u| { universe_map[u.as_usize()] })
                            } else if kind.is_existential() {
                                match opt_values[BoundVar::new(var_values.len())] {
                                    Some(k) => k,
                                    None =>
                                        self.instantiate_canonical_var(cause.span, kind,
                                            &var_values, |u| { universe_map[u.as_usize()] }),
                                }
                            } else {
                                opt_values[BoundVar::new(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/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/compiler/rustc_infer/src/infer/canonical/query_response.rs:531",
                                        "rustc_infer::infer::canonical::query_response",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                                        ::tracing_core::__macro_support::Option::Some(531u32),
                                        ::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.at(cause,
                                    param_env).eq(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))]
423    fn query_response_instantiation_guess<R>(
424        &self,
425        cause: &ObligationCause<'tcx>,
426        param_env: ty::ParamEnv<'tcx>,
427        original_values: &OriginalQueryValues<'tcx>,
428        query_response: &Canonical<'tcx, QueryResponse<'tcx, R>>,
429    ) -> InferResult<'tcx, CanonicalVarValues<'tcx>>
430    where
431        R: Debug + TypeFoldable<TyCtxt<'tcx>>,
432    {
433        // For each new universe created in the query result that did
434        // not appear in the original query, create a local
435        // superuniverse.
436        let mut universe_map = original_values.universe_map.clone();
437        let num_universes_in_query = original_values.universe_map.len();
438        let num_universes_in_response = query_response.max_universe.as_usize() + 1;
439        for _ in num_universes_in_query..num_universes_in_response {
440            universe_map.push(self.create_next_universe());
441        }
442        assert!(!universe_map.is_empty()); // always have the root universe
443        assert_eq!(universe_map[ty::UniverseIndex::ROOT.as_usize()], ty::UniverseIndex::ROOT);
444
445        // Every canonical query result includes values for each of
446        // the inputs to the query. Therefore, we begin by unifying
447        // these values with the original inputs that were
448        // canonicalized.
449        let result_values = &query_response.value.var_values;
450        assert_eq!(original_values.var_values.len(), result_values.len());
451
452        // Quickly try to find initial values for the canonical
453        // variables in the result in terms of the query. We do this
454        // by iterating down the values that the query gave to each of
455        // the canonical inputs. If we find that one of those values
456        // is directly equal to one of the canonical variables in the
457        // result, then we can type the corresponding value from the
458        // input. See the example above.
459        let mut opt_values: IndexVec<BoundVar, Option<GenericArg<'tcx>>> =
460            IndexVec::from_elem_n(None, query_response.var_kinds.len());
461
462        for (original_value, result_value) in iter::zip(&original_values.var_values, result_values)
463        {
464            match result_value.kind() {
465                GenericArgKind::Type(result_value) => {
466                    // We disable the instantiation guess for inference variables
467                    // and only use it for placeholders. We need to handle the
468                    // `sub_root` of type inference variables which would make this
469                    // more involved. They are also a lot rarer than region variables.
470                    if let ty::Bound(index_kind, b) = *result_value.kind()
471                        && !matches!(
472                            query_response.var_kinds[b.var.as_usize()],
473                            CanonicalVarKind::Ty { .. }
474                        )
475                    {
476                        // We only allow a `Canonical` index in generic parameters.
477                        assert!(matches!(index_kind, ty::BoundVarIndexKind::Canonical));
478                        opt_values[b.var] = Some(*original_value);
479                    }
480                }
481                GenericArgKind::Lifetime(result_value) => {
482                    if let ty::ReBound(index_kind, b) = result_value.kind() {
483                        // We only allow a `Canonical` index in generic parameters.
484                        assert!(matches!(index_kind, ty::BoundVarIndexKind::Canonical));
485                        opt_values[b.var] = Some(*original_value);
486                    }
487                }
488                GenericArgKind::Const(result_value) => {
489                    if let ty::ConstKind::Bound(index_kind, b) = result_value.kind() {
490                        // We only allow a `Canonical` index in generic parameters.
491                        assert!(matches!(index_kind, ty::BoundVarIndexKind::Canonical));
492                        opt_values[b.var] = Some(*original_value);
493                    }
494                }
495            }
496        }
497
498        // Create result arguments: if we found a value for a
499        // given variable in the loop above, use that. Otherwise, use
500        // a fresh inference variable.
501        let tcx = self.tcx;
502        let var_kinds = query_response.var_kinds;
503        let var_values = CanonicalVarValues::instantiate(tcx, var_kinds, |var_values, kind| {
504            if kind.universe() != ty::UniverseIndex::ROOT {
505                // A variable from inside a binder of the query. While ideally these shouldn't
506                // exist at all, we have to deal with them for now.
507                self.instantiate_canonical_var(cause.span, kind, &var_values, |u| {
508                    universe_map[u.as_usize()]
509                })
510            } else if kind.is_existential() {
511                match opt_values[BoundVar::new(var_values.len())] {
512                    Some(k) => k,
513                    None => self.instantiate_canonical_var(cause.span, kind, &var_values, |u| {
514                        universe_map[u.as_usize()]
515                    }),
516                }
517            } else {
518                // For placeholders which were already part of the input, we simply map this
519                // universal bound variable back the placeholder of the input.
520                opt_values[BoundVar::new(var_values.len())]
521                    .expect("expected placeholder to be unified with itself during response")
522            }
523        });
524
525        let mut obligations = PredicateObligations::new();
526
527        // Carry all newly resolved opaque types to the caller's scope
528        for &(a, b) in &query_response.value.opaque_types {
529            let a = instantiate_value(self.tcx, &var_values, a);
530            let b = instantiate_value(self.tcx, &var_values, b);
531            debug!(?a, ?b, "constrain opaque type");
532            // We use equate here instead of, for example, just registering the
533            // opaque type's hidden value directly, because the hidden type may have been an inference
534            // variable that got constrained to the opaque type itself. In that case we want to equate
535            // the generic args of the opaque with the generic params of its hidden type version.
536            obligations.extend(
537                self.at(cause, param_env)
538                    .eq(
539                        DefineOpaqueTypes::Yes,
540                        Ty::new_opaque(self.tcx, ty::IsRigid::No, a.def_id.to_def_id(), a.args),
541                        b,
542                    )?
543                    .obligations,
544            );
545        }
546
547        Ok(InferOk { value: var_values, obligations })
548    }
549
550    /// Given a "guess" at the values for the canonical variables in
551    /// the input, try to unify with the *actual* values found in the
552    /// query result. Often, but not always, this is a no-op, because
553    /// we already found the mapping in the "guessing" step.
554    ///
555    /// See also: [`Self::query_response_instantiation_guess`]
556    fn unify_query_response_instantiation_guess<R>(
557        &self,
558        cause: &ObligationCause<'tcx>,
559        param_env: ty::ParamEnv<'tcx>,
560        original_values: &OriginalQueryValues<'tcx>,
561        result_args: &CanonicalVarValues<'tcx>,
562        query_response: &Canonical<'tcx, QueryResponse<'tcx, R>>,
563    ) -> InferResult<'tcx, ()>
564    where
565        R: Debug + TypeFoldable<TyCtxt<'tcx>>,
566    {
567        // A closure that yields the result value for the given
568        // canonical variable; this is taken from
569        // `query_response.var_values` after applying the instantiation
570        // by `result_args`.
571        let instantiated_query_response = |index: BoundVar| -> GenericArg<'tcx> {
572            query_response.instantiate_projected(self.tcx, result_args, |v| v.var_values[index])
573        };
574
575        // Unify the original value for each variable with the value
576        // taken from `query_response` (after applying `result_args`).
577        self.unify_canonical_vars(cause, param_env, original_values, instantiated_query_response)
578    }
579
580    /// Given two sets of values for the same set of canonical variables, unify them.
581    /// The second set is produced lazily by supplying indices from the first set.
582    fn unify_canonical_vars(
583        &self,
584        cause: &ObligationCause<'tcx>,
585        param_env: ty::ParamEnv<'tcx>,
586        variables1: &OriginalQueryValues<'tcx>,
587        variables2: impl Fn(BoundVar) -> GenericArg<'tcx>,
588    ) -> InferResult<'tcx, ()> {
589        let mut obligations = PredicateObligations::new();
590        for (index, value1) in variables1.var_values.iter().enumerate() {
591            let value2 = variables2(BoundVar::new(index));
592
593            match (value1.kind(), value2.kind()) {
594                (GenericArgKind::Type(v1), GenericArgKind::Type(v2)) => {
595                    obligations.extend(
596                        self.at(cause, param_env)
597                            .eq(DefineOpaqueTypes::Yes, v1, v2)?
598                            .into_obligations(),
599                    );
600                }
601                (GenericArgKind::Lifetime(re1), GenericArgKind::Lifetime(re2))
602                    if re1.is_erased() && re2.is_erased() =>
603                {
604                    // no action needed
605                }
606                (GenericArgKind::Lifetime(v1), GenericArgKind::Lifetime(v2)) => {
607                    self.inner.borrow_mut().unwrap_region_constraints().make_eqregion(
608                        SubregionOrigin::RelateRegionParamBound(cause.span, None),
609                        v1,
610                        v2,
611                        ty::VisibleForLeakCheck::Yes,
612                    );
613                }
614                (GenericArgKind::Const(v1), GenericArgKind::Const(v2)) => {
615                    let ok = self.at(cause, param_env).eq(DefineOpaqueTypes::Yes, v1, v2)?;
616                    obligations.extend(ok.into_obligations());
617                }
618                _ => {
619                    ::rustc_middle::util::bug::bug_fmt(format_args!("kind mismatch, cannot unify {0:?} and {1:?}",
        value1, value2));bug!("kind mismatch, cannot unify {:?} and {:?}", value1, value2,);
620                }
621            }
622        }
623        Ok(InferOk { value: (), obligations })
624    }
625}
626
627/// Given the region obligations and constraints scraped from the infcx,
628/// creates query region constraints.
629pub fn make_query_region_constraints<'tcx>(
630    outlives_obligations: Vec<TypeOutlivesConstraint<'tcx>>,
631    region_constraints: &RegionConstraintData<'tcx>,
632    assumptions: Vec<ty::ArgOutlivesClause<'tcx>>,
633    solver_constraints: ty::region_constraint::RegionConstraint<TyCtxt<'tcx>>,
634) -> QueryRegionConstraints<'tcx> {
635    let RegionConstraintData { constraints, verifys } = region_constraints;
636
637    if !verifys.is_empty() {
    ::core::panicking::panic("assertion failed: verifys.is_empty()")
};assert!(verifys.is_empty());
638
639    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/compiler/rustc_infer/src/infer/canonical/query_response.rs:639",
                        "rustc_infer::infer::canonical::query_response",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4aa1fbcf467cf38ce58abfa8eb9213a789c5381c/compiler/rustc_infer/src/infer/canonical/query_response.rs"),
                        ::tracing_core::__macro_support::Option::Some(639u32),
                        ::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);
640
641    let constraints: Vec<QueryRegionConstraint<'tcx>> = constraints
642        .iter()
643        .map(|(c, origin)| match c.kind {
644            ConstraintKind::VarSubVar
645            | ConstraintKind::RegSubVar
646            | ConstraintKind::VarSubReg
647            | ConstraintKind::RegSubReg => {
648                // Swap regions because we are going from sub (<=) to outlives (>=).
649                let constraint = ty::OutlivesClause(c.sup.into(), c.sub).into();
650                QueryRegionConstraint {
651                    constraint,
652                    category: origin.to_constraint_category(),
653                    visible_for_leak_check: c.visible_for_leak_check,
654                }
655            }
656
657            ConstraintKind::VarEqVar | ConstraintKind::VarEqReg | ConstraintKind::RegEqReg => {
658                let constraint = ty::RegionEqPredicate(c.sup, c.sub).into();
659                QueryRegionConstraint {
660                    constraint,
661                    category: origin.to_constraint_category(),
662                    visible_for_leak_check: c.visible_for_leak_check,
663                }
664            }
665        })
666        .chain(outlives_obligations.into_iter().map(
667            |TypeOutlivesConstraint { sub_region, sup_type, origin }| {
668                QueryRegionConstraint {
669                    constraint: ty::OutlivesClause(sup_type.into(), sub_region).into(),
670                    category: origin.to_constraint_category(),
671                    // We don't do leak checks for type outlives
672                    visible_for_leak_check: ty::VisibleForLeakCheck::Unreachable,
673                }
674            },
675        ))
676        .collect();
677
678    QueryRegionConstraints { constraints, assumptions, solver_constraints }
679}