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