rustc_trait_selection/traits/query/type_op/
mod.rs

1use std::fmt;
2
3use rustc_errors::ErrorGuaranteed;
4use rustc_infer::traits::PredicateObligations;
5use rustc_middle::traits::query::NoSolution;
6use rustc_middle::ty::fold::TypeFoldable;
7use rustc_middle::ty::{ParamEnvAnd, TyCtxt};
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 implied_outlives_bounds;
20pub mod normalize;
21pub mod outlives;
22pub mod prove_predicate;
23
24pub use rustc_middle::traits::query::type_op::*;
25
26use self::custom::scrape_region_constraints;
27
28/// "Type ops" are used in NLL to perform some particular action and
29/// extract out the resulting region constraints (or an error if it
30/// cannot be completed).
31pub trait TypeOp<'tcx>: Sized + fmt::Debug {
32    type Output: fmt::Debug;
33    type ErrorInfo;
34
35    /// Processes the operation and all resulting obligations,
36    /// returning the final result along with any region constraints
37    /// (they will be given over to the NLL region solver).
38    fn fully_perform(
39        self,
40        infcx: &InferCtxt<'tcx>,
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 let Some(result) = QueryTypeOp::try_fast_path(infcx.tcx, &query_key) {
113            return Ok((result, None, PredicateObligations::new(), Certainty::Proven));
114        }
115
116        let mut canonical_var_values = OriginalQueryValues::default();
117        let old_param_env = query_key.param_env;
118        let canonical_self = infcx.canonicalize_query(query_key, &mut canonical_var_values);
119        let canonical_result = Self::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                output_query_region_constraints,
128            )?;
129
130        Ok((value, Some(canonical_self), obligations, canonical_result.value.certainty))
131    }
132}
133
134impl<'tcx, Q> TypeOp<'tcx> for ParamEnvAnd<'tcx, Q>
135where
136    Q: QueryTypeOp<'tcx>,
137{
138    type Output = Q::QueryResponse;
139    type ErrorInfo = CanonicalQueryInput<'tcx, ParamEnvAnd<'tcx, Q>>;
140
141    fn fully_perform(
142        self,
143        infcx: &InferCtxt<'tcx>,
144        span: Span,
145    ) -> Result<TypeOpOutput<'tcx, Self>, ErrorGuaranteed> {
146        // In the new trait solver, query type ops are performed locally. This
147        // is because query type ops currently use the old canonicalizer, and
148        // that doesn't preserve things like opaques which have been registered
149        // during MIR typeck. Even after the old canonicalizer is gone, it's
150        // probably worthwhile just keeping this run-locally logic, since we
151        // probably don't gain much from caching here given the new solver does
152        // caching internally.
153        if infcx.next_trait_solver() {
154            return Ok(scrape_region_constraints(
155                infcx,
156                |ocx| QueryTypeOp::perform_locally_with_next_solver(ocx, self, span),
157                "query type op",
158                span,
159            )?
160            .0);
161        }
162
163        let mut error_info = None;
164        let mut region_constraints = QueryRegionConstraints::default();
165
166        // HACK(type_alias_impl_trait): When moving an opaque type to hidden type mapping from the query to the current inferctxt,
167        // we sometimes end up with `Opaque<'a> = Opaque<'b>` instead of an actual hidden type. In that case we don't register a
168        // hidden type but just equate the lifetimes. Thus we need to scrape the region constraints even though we're also manually
169        // collecting region constraints via `region_constraints`.
170        let (mut output, _) = scrape_region_constraints(
171            infcx,
172            |ocx| {
173                let (output, ei, obligations, _) =
174                    Q::fully_perform_into(self, infcx, &mut region_constraints, span)?;
175                error_info = ei;
176
177                ocx.register_obligations(obligations);
178                Ok(output)
179            },
180            "fully_perform",
181            span,
182        )?;
183        output.error_info = error_info;
184        if let Some(QueryRegionConstraints { outlives }) = output.constraints {
185            region_constraints.outlives.extend(outlives.iter().cloned());
186        }
187        output.constraints = if region_constraints.is_empty() {
188            None
189        } else {
190            Some(infcx.tcx.arena.alloc(region_constraints))
191        };
192        Ok(output)
193    }
194}