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