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