Skip to main content

rustc_infer/infer/canonical/
query_response.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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