Skip to main content

rustc_trait_selection/traits/query/type_op/
mod.rs

1use std::fmt;
2
3use rustc_errors::ErrorGuaranteed;
4use rustc_hir::def_id::LocalDefId;
5use rustc_middle::traits::query::NoSolution;
6use rustc_middle::ty::{ParamEnvAnd, TyCtxt, TypeFoldable};
7use rustc_span::Span;
8
9use crate::infer::canonical::{
10    CanonicalQueryInput, CanonicalQueryResponse, OriginalQueryValues, QueryRegionConstraints,
11};
12use crate::infer::{InferCtxt, InferOk};
13use crate::traits::ObligationCause;
14
15pub mod ascribe_user_type;
16pub mod custom;
17pub mod normalize;
18pub mod outlives;
19pub mod prove_predicate;
20
21pub use rustc_middle::traits::query::type_op::*;
22
23use self::custom::scrape_region_constraints;
24
25/// "Type ops" are used in NLL to perform some particular action and
26/// extract out the resulting region constraints (or an error if it
27/// cannot be completed).
28pub trait TypeOp<'tcx>: Sized + fmt::Debug {
29    type Output: fmt::Debug;
30    type ErrorInfo;
31
32    /// Processes the operation and all resulting obligations,
33    /// returning the final result along with any region constraints
34    /// (they will be given over to the NLL region solver).
35    fn fully_perform(
36        self,
37        infcx: &InferCtxt<'tcx>,
38        root_def_id: LocalDefId,
39        span: Span,
40    ) -> Result<TypeOpOutput<'tcx, Self>, ErrorGuaranteed>;
41}
42
43/// The output from performing a type op
44pub struct TypeOpOutput<'tcx, Op: TypeOp<'tcx>> {
45    /// The output from the type op.
46    pub output: Op::Output,
47    /// Any region constraints from performing the type op.
48    pub constraints: Option<&'tcx QueryRegionConstraints<'tcx>>,
49    /// Used for error reporting to be able to rerun the query
50    pub error_info: Option<Op::ErrorInfo>,
51}
52
53/// "Query type ops" are type ops that are implemented using a
54/// [canonical query][c]. The `Self` type here contains the kernel of
55/// information needed to do the operation -- `TypeOp` is actually
56/// implemented for `ParamEnvAnd<Self>`, since we always need to bring
57/// along a parameter environment as well. For query type-ops, we will
58/// first canonicalize the key and then invoke the query on the tcx,
59/// which produces the resulting query region constraints.
60///
61/// [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html
62pub trait QueryTypeOp<'tcx>: fmt::Debug + Copy + TypeFoldable<TyCtxt<'tcx>> + 'tcx {
63    type QueryResponse: TypeFoldable<TyCtxt<'tcx>> + PartialEq;
64
65    /// Give query the option for a simple fast path that never
66    /// actually hits the tcx cache lookup etc. Return `Some(r)` with
67    /// a final result or `None` to do the full path.
68    fn try_fast_path(
69        infcx: &InferCtxt<'tcx>,
70        key: &ParamEnvAnd<'tcx, Self>,
71    ) -> Option<Self::QueryResponse>;
72
73    /// Performs the actual query with the canonicalized key -- the
74    /// real work happens here. This method is not given an `infcx`
75    /// because it shouldn't need one -- and if it had access to one,
76    /// it might do things like invoke `sub_regions`, which would be
77    /// bad, because it would create subregion relationships that are
78    /// not captured in the return value.
79    fn perform_query(
80        tcx: TyCtxt<'tcx>,
81        canonicalized: CanonicalQueryInput<'tcx, ParamEnvAnd<'tcx, Self>>,
82    ) -> Result<CanonicalQueryResponse<'tcx, Self::QueryResponse>, NoSolution>;
83}
84
85impl<'tcx, Q> TypeOp<'tcx> for ParamEnvAnd<'tcx, Q>
86where
87    Q: QueryTypeOp<'tcx>,
88{
89    type Output = Q::QueryResponse;
90    type ErrorInfo = CanonicalQueryInput<'tcx, ParamEnvAnd<'tcx, Q>>;
91
92    fn fully_perform(
93        self,
94        infcx: &InferCtxt<'tcx>,
95        root_def_id: LocalDefId,
96        span: Span,
97    ) -> Result<TypeOpOutput<'tcx, Self>, ErrorGuaranteed> {
98        if !infcx.disable_trait_solver_fast_paths()
99            && let Some(value) = QueryTypeOp::try_fast_path(infcx, &self)
100        {
101            if true {
    {
        match (&value, &infcx.deeply_resolve_ignoring_regions(value.clone()))
            {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(value, infcx.deeply_resolve_ignoring_regions(value.clone()));
102
103            return Ok(TypeOpOutput { output: value, constraints: None, error_info: None });
104        }
105
106        let mut error_info = None;
107        let mut region_constraints = QueryRegionConstraints::default();
108
109        // HACK(type_alias_impl_trait): When moving an opaque type to hidden type mapping from the
110        // query to the current inferctxt, we sometimes end up with `Opaque<'a> = Opaque<'b>`
111        // instead of an actual hidden type. In that case we don't register a hidden type but just
112        // equate the lifetimes. Thus we need to scrape the region constraints even though we're
113        // also manually collecting region constraints via `region_constraints`.
114        let (mut output, _) =
115            scrape_region_constraints(infcx, root_def_id, "fully_perform", span, |ocx| {
116                let mut canonical_var_values = OriginalQueryValues::default();
117                let old_param_env = self.param_env;
118                let canonical_self = infcx.canonicalize_query(self, &mut canonical_var_values);
119                let canonical_result = Q::perform_query(infcx.tcx, canonical_self)?;
120
121                let InferOk { value, obligations } = infcx
122                    .instantiate_nll_query_response_and_region_obligations(
123                        &ObligationCause::dummy_with_span(span),
124                        old_param_env,
125                        &canonical_var_values,
126                        canonical_result,
127                        &mut region_constraints,
128                    )?;
129
130                error_info = Some(canonical_self);
131                ocx.register_obligations(obligations);
132                Ok(value)
133            })?;
134        output.error_info = error_info;
135
136        if let Some(QueryRegionConstraints { constraints, assumptions }) = output.constraints {
137            region_constraints.constraints.extend(constraints.iter().cloned());
138            region_constraints.assumptions.extend(assumptions.iter().cloned());
139        }
140        output.constraints = if region_constraints.is_empty() {
141            None
142        } else {
143            Some(infcx.tcx.arena.alloc(region_constraints))
144        };
145        Ok(output)
146    }
147}