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