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;
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::{ObligationCause, PredicateObligations, ScrubbedTraitError, TraitEngine};
32
33impl<'tcx> InferCtxt<'tcx> {
34    /// This method is meant to be invoked as the final step of a canonical query
35    /// implementation. It is given:
36    ///
37    /// - the instantiated variables `inference_vars` created from the query key
38    /// - the result `answer` of the query
39    /// - a fulfillment context `fulfill_cx` that may contain various obligations which
40    ///   have yet to be proven.
41    ///
42    /// Given this, the function will process the obligations pending
43    /// in `fulfill_cx`:
44    ///
45    /// - If all the obligations can be proven successfully, it will
46    ///   package up any resulting region obligations (extracted from
47    ///   `infcx`) along with the fully resolved value `answer` into a
48    ///   query result (which is then itself canonicalized).
49    /// - If some obligations can be neither proven nor disproven, then
50    ///   the same thing happens, but the resulting query is marked as ambiguous.
51    /// - Finally, if any of the obligations result in a hard error,
52    ///   then `Err(NoSolution)` is returned.
53    #[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(53u32),
                                    ::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(&[]) })
                } 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:65",
                                    "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(65u32),
                                    ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("query_response = {0:#?}",
                                                                query_response) as &dyn 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: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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("canonical_result = {0:#?}",
                                                                canonical_result) as &dyn Value))])
                        });
                } else { ; }
            };
            Ok(self.tcx.arena.alloc(canonical_result))
        }
    }
}#[instrument(skip(self, inference_vars, answer, fulfill_cx), level = "trace")]
54    pub fn make_canonicalized_query_response<T>(
55        &self,
56        inference_vars: CanonicalVarValues<'tcx>,
57        answer: T,
58        fulfill_cx: &mut dyn TraitEngine<'tcx, ScrubbedTraitError<'tcx>>,
59    ) -> Result<CanonicalQueryResponse<'tcx, T>, NoSolution>
60    where
61        T: Debug + TypeFoldable<TyCtxt<'tcx>>,
62        Canonical<'tcx, QueryResponse<'tcx, T>>: ArenaAllocatable<'tcx>,
63    {
64        let query_response = self.make_query_response(inference_vars, answer, fulfill_cx)?;
65        debug!("query_response = {:#?}", query_response);
66        let canonical_result = self.canonicalize_response(query_response);
67        debug!("canonical_result = {:#?}", canonical_result);
68
69        Ok(self.tcx.arena.alloc(canonical_result))
70    }
71
72    /// A version of `make_canonicalized_query_response` that does
73    /// not pack in obligations, for contexts that want to drop
74    /// pending obligations instead of treating them as an ambiguity (e.g.
75    /// typeck "probing" contexts).
76    ///
77    /// If you DO want to keep track of pending obligations (which
78    /// include all region obligations, so this includes all cases
79    /// that care about regions) with this function, you have to
80    /// do it yourself, by e.g., having them be a part of the answer.
81    pub fn make_query_response_ignoring_pending_obligations<T>(
82        &self,
83        inference_vars: CanonicalVarValues<'tcx>,
84        answer: T,
85        prev_entries: OpaqueTypeStorageEntries,
86    ) -> Canonical<'tcx, QueryResponse<'tcx, T>>
87    where
88        T: Debug + TypeFoldable<TyCtxt<'tcx>>,
89    {
90        // While we ignore region constraints and pending obligations,
91        // we do return constrained opaque types to avoid unconstrained
92        // inference variables in the response. This is important as we want
93        // to check that opaques in deref steps stay unconstrained.
94        //
95        // This doesn't handle the more general case for non-opaques as
96        // ambiguous `Projection` obligations have same the issue.
97        let opaque_types = if self.next_trait_solver() {
98            self.inner
99                .borrow_mut()
100                .opaque_type_storage
101                .opaque_types_added_since(prev_entries)
102                .map(|(k, v)| (k, v.ty))
103                .collect()
104        } else {
105            ::alloc::vec::Vec::new()vec![]
106        };
107
108        self.canonicalize_response(QueryResponse {
109            var_values: inference_vars,
110            region_constraints: QueryRegionConstraints::default(),
111            certainty: Certainty::Proven, // Ambiguities are OK!
112            opaque_types,
113            value: answer,
114        })
115    }
116
117    /// Helper for `make_canonicalized_query_response` that does
118    /// everything up until the final canonicalization.
119    #[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(119u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::canonical::query_response"),
                                    ::tracing_core::field::FieldSet::new(&["inference_vars",
                                                    "answer"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&inference_vars)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&answer)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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