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;
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, ObligationCtxt};
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>>;
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        tcx: TyCtxt<'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    /// In the new trait solver, we already do caching in the solver itself,
87    /// so there's no need to canonicalize and cache via the query system.
88    /// Additionally, even if we were to canonicalize, we'd still need to
89    /// make sure to feed it predefined opaque types and the defining anchor
90    /// and that would require duplicating all of the tcx queries. Instead,
91    /// just perform these ops locally.
92    fn perform_locally_with_next_solver(
93        ocx: &ObligationCtxt<'_, 'tcx>,
94        key: ParamEnvAnd<'tcx, Self>,
95        span: Span,
96    ) -> Result<Self::QueryResponse, NoSolution>;
97
98    fn fully_perform_into(
99        query_key: ParamEnvAnd<'tcx, Self>,
100        infcx: &InferCtxt<'tcx>,
101        output_query_region_constraints: &mut QueryRegionConstraints<'tcx>,
102        span: Span,
103    ) -> Result<
104        (
105            Self::QueryResponse,
106            Option<CanonicalQueryInput<'tcx, ParamEnvAnd<'tcx, Self>>>,
107            PredicateObligations<'tcx>,
108            Certainty,
109        ),
110        NoSolution,
111    > {
112        if !infcx.disable_trait_solver_fast_paths()
113            && let Some(result) = QueryTypeOp::try_fast_path(infcx.tcx, &query_key)
114        {
115            return Ok((result, None, PredicateObligations::new(), Certainty::Proven));
116        }
117
118        let mut canonical_var_values = OriginalQueryValues::default();
119        let old_param_env = query_key.param_env;
120        let canonical_self = infcx.canonicalize_query(query_key, &mut canonical_var_values);
121        let canonical_result = Self::perform_query(infcx.tcx, canonical_self)?;
122
123        let InferOk { value, obligations } = infcx
124            .instantiate_nll_query_response_and_region_obligations(
125                &ObligationCause::dummy_with_span(span),
126                old_param_env,
127                &canonical_var_values,
128                canonical_result,
129                output_query_region_constraints,
130            )?;
131
132        Ok((value, Some(canonical_self), obligations, canonical_result.value.certainty))
133    }
134}
135
136impl<'tcx, Q> TypeOp<'tcx> for ParamEnvAnd<'tcx, Q>
137where
138    Q: QueryTypeOp<'tcx>,
139{
140    type Output = Q::QueryResponse;
141    type ErrorInfo = CanonicalQueryInput<'tcx, ParamEnvAnd<'tcx, Q>>;
142
143    fn fully_perform(
144        self,
145        infcx: &InferCtxt<'tcx>,
146        root_def_id: LocalDefId,
147        span: Span,
148    ) -> Result<TypeOpOutput<'tcx, Self>, ErrorGuaranteed> {
149        let mut error_info = None;
150        let mut region_constraints = QueryRegionConstraints::default();
151
152        // HACK(type_alias_impl_trait): When moving an opaque type to hidden type mapping from the query to the current inferctxt,
153        // we sometimes end up with `Opaque<'a> = Opaque<'b>` instead of an actual hidden type. In that case we don't register a
154        // hidden type but just equate the lifetimes. Thus we need to scrape the region constraints even though we're also manually
155        // collecting region constraints via `region_constraints`.
156        let (mut output, _) =
157            scrape_region_constraints(infcx, root_def_id, "fully_perform", span, |ocx| {
158                let (output, ei, obligations, _) =
159                    Q::fully_perform_into(self, infcx, &mut region_constraints, span)?;
160                error_info = ei;
161
162                ocx.register_obligations(obligations);
163                Ok(output)
164            })?;
165        output.error_info = error_info;
166        if let Some(QueryRegionConstraints { constraints, assumptions }) = output.constraints {
167            region_constraints.constraints.extend(constraints.iter().cloned());
168            region_constraints.assumptions.extend(assumptions.iter().cloned());
169        }
170        output.constraints = if region_constraints.is_empty() {
171            None
172        } else {
173            Some(infcx.tcx.arena.alloc(region_constraints))
174        };
175        Ok(output)
176    }
177}