]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/at.rs
Auto merge of #78781 - eddyb:measureme-rdpmc, r=oli-obk
[rust.git] / compiler / rustc_infer / src / infer / at.rs
1 //! A nice interface for working with the infcx. The basic idea is to
2 //! do `infcx.at(cause, param_env)`, which sets the "cause" of the
3 //! operation as well as the surrounding parameter environment. Then
4 //! you can do something like `.sub(a, b)` or `.eq(a, b)` to create a
5 //! subtype or equality relationship respectively. The first argument
6 //! is always the "expected" output from the POV of diagnostics.
7 //!
8 //! Examples:
9 //! ```ignore (fragment)
10 //!     infcx.at(cause, param_env).sub(a, b)
11 //!     // requires that `a <: b`, with `a` considered the "expected" type
12 //!
13 //!     infcx.at(cause, param_env).sup(a, b)
14 //!     // requires that `b <: a`, with `a` considered the "expected" type
15 //!
16 //!     infcx.at(cause, param_env).eq(a, b)
17 //!     // requires that `a == b`, with `a` considered the "expected" type
18 //! ```
19 //! For finer-grained control, you can also do use `trace`:
20 //! ```ignore (fragment)
21 //!     infcx.at(...).trace(a, b).sub(&c, &d)
22 //! ```
23 //! This will set `a` and `b` as the "root" values for
24 //! error-reporting, but actually operate on `c` and `d`. This is
25 //! sometimes useful when the types of `c` and `d` are not traceable
26 //! things. (That system should probably be refactored.)
27
28 use super::*;
29
30 use rustc_middle::ty::relate::{Relate, TypeRelation};
31 use rustc_middle::ty::{Const, ImplSubject};
32
33 pub struct At<'a, 'tcx> {
34     pub infcx: &'a InferCtxt<'a, 'tcx>,
35     pub cause: &'a ObligationCause<'tcx>,
36     pub param_env: ty::ParamEnv<'tcx>,
37     /// Whether we should define opaque types
38     /// or just treat them opaquely.
39     /// Currently only used to prevent predicate
40     /// matching from matching anything against opaque
41     /// types.
42     pub define_opaque_types: bool,
43 }
44
45 pub struct Trace<'a, 'tcx> {
46     at: At<'a, 'tcx>,
47     a_is_expected: bool,
48     trace: TypeTrace<'tcx>,
49 }
50
51 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
52     #[inline]
53     pub fn at(
54         &'a self,
55         cause: &'a ObligationCause<'tcx>,
56         param_env: ty::ParamEnv<'tcx>,
57     ) -> At<'a, 'tcx> {
58         At { infcx: self, cause, param_env, define_opaque_types: true }
59     }
60
61     /// Forks the inference context, creating a new inference context with the same inference
62     /// variables in the same state. This can be used to "branch off" many tests from the same
63     /// common state. Used in coherence.
64     pub fn fork(&self) -> Self {
65         Self {
66             tcx: self.tcx,
67             defining_use_anchor: self.defining_use_anchor,
68             in_progress_typeck_results: self.in_progress_typeck_results,
69             inner: self.inner.clone(),
70             skip_leak_check: self.skip_leak_check.clone(),
71             lexical_region_resolutions: self.lexical_region_resolutions.clone(),
72             selection_cache: self.selection_cache.clone(),
73             evaluation_cache: self.evaluation_cache.clone(),
74             reported_trait_errors: self.reported_trait_errors.clone(),
75             reported_closure_mismatch: self.reported_closure_mismatch.clone(),
76             tainted_by_errors_flag: self.tainted_by_errors_flag.clone(),
77             err_count_on_creation: self.err_count_on_creation,
78             in_snapshot: self.in_snapshot.clone(),
79             universe: self.universe.clone(),
80         }
81     }
82 }
83
84 pub trait ToTrace<'tcx>: Relate<'tcx> + Copy {
85     fn to_trace(
86         tcx: TyCtxt<'tcx>,
87         cause: &ObligationCause<'tcx>,
88         a_is_expected: bool,
89         a: Self,
90         b: Self,
91     ) -> TypeTrace<'tcx>;
92 }
93
94 impl<'a, 'tcx> At<'a, 'tcx> {
95     pub fn define_opaque_types(self, define_opaque_types: bool) -> Self {
96         Self { define_opaque_types, ..self }
97     }
98
99     /// Hacky routine for equating two impl headers in coherence.
100     pub fn eq_impl_headers(
101         self,
102         expected: &ty::ImplHeader<'tcx>,
103         actual: &ty::ImplHeader<'tcx>,
104     ) -> InferResult<'tcx, ()> {
105         debug!("eq_impl_header({:?} = {:?})", expected, actual);
106         match (expected.trait_ref, actual.trait_ref) {
107             (Some(a_ref), Some(b_ref)) => self.eq(a_ref, b_ref),
108             (None, None) => self.eq(expected.self_ty, actual.self_ty),
109             _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
110         }
111     }
112
113     /// Makes `a <: b`, where `a` may or may not be expected.
114     ///
115     /// See [`At::trace_exp`] and [`Trace::sub`] for a version of
116     /// this method that only requires `T: Relate<'tcx>`
117     pub fn sub_exp<T>(self, a_is_expected: bool, a: T, b: T) -> InferResult<'tcx, ()>
118     where
119         T: ToTrace<'tcx>,
120     {
121         self.trace_exp(a_is_expected, a, b).sub(a, b)
122     }
123
124     /// Makes `actual <: expected`. For example, if type-checking a
125     /// call like `foo(x)`, where `foo: fn(i32)`, you might have
126     /// `sup(i32, x)`, since the "expected" type is the type that
127     /// appears in the signature.
128     ///
129     /// See [`At::trace`] and [`Trace::sub`] for a version of
130     /// this method that only requires `T: Relate<'tcx>`
131     pub fn sup<T>(self, expected: T, actual: T) -> InferResult<'tcx, ()>
132     where
133         T: ToTrace<'tcx>,
134     {
135         self.sub_exp(false, actual, expected)
136     }
137
138     /// Makes `expected <: actual`.
139     ///
140     /// See [`At::trace`] and [`Trace::sub`] for a version of
141     /// this method that only requires `T: Relate<'tcx>`
142     pub fn sub<T>(self, expected: T, actual: T) -> InferResult<'tcx, ()>
143     where
144         T: ToTrace<'tcx>,
145     {
146         self.sub_exp(true, expected, actual)
147     }
148
149     /// Makes `expected <: actual`.
150     ///
151     /// See [`At::trace_exp`] and [`Trace::eq`] for a version of
152     /// this method that only requires `T: Relate<'tcx>`
153     pub fn eq_exp<T>(self, a_is_expected: bool, a: T, b: T) -> InferResult<'tcx, ()>
154     where
155         T: ToTrace<'tcx>,
156     {
157         self.trace_exp(a_is_expected, a, b).eq(a, b)
158     }
159
160     /// Makes `expected <: actual`.
161     ///
162     /// See [`At::trace`] and [`Trace::eq`] for a version of
163     /// this method that only requires `T: Relate<'tcx>`
164     pub fn eq<T>(self, expected: T, actual: T) -> InferResult<'tcx, ()>
165     where
166         T: ToTrace<'tcx>,
167     {
168         self.trace(expected, actual).eq(expected, actual)
169     }
170
171     pub fn relate<T>(self, expected: T, variance: ty::Variance, actual: T) -> InferResult<'tcx, ()>
172     where
173         T: ToTrace<'tcx>,
174     {
175         match variance {
176             ty::Variance::Covariant => self.sub(expected, actual),
177             ty::Variance::Invariant => self.eq(expected, actual),
178             ty::Variance::Contravariant => self.sup(expected, actual),
179
180             // We could make this make sense but it's not readily
181             // exposed and I don't feel like dealing with it. Note
182             // that bivariance in general does a bit more than just
183             // *nothing*, it checks that the types are the same
184             // "modulo variance" basically.
185             ty::Variance::Bivariant => panic!("Bivariant given to `relate()`"),
186         }
187     }
188
189     /// Computes the least-upper-bound, or mutual supertype, of two
190     /// values. The order of the arguments doesn't matter, but since
191     /// this can result in an error (e.g., if asked to compute LUB of
192     /// u32 and i32), it is meaningful to call one of them the
193     /// "expected type".
194     ///
195     /// See [`At::trace`] and [`Trace::lub`] for a version of
196     /// this method that only requires `T: Relate<'tcx>`
197     pub fn lub<T>(self, expected: T, actual: T) -> InferResult<'tcx, T>
198     where
199         T: ToTrace<'tcx>,
200     {
201         self.trace(expected, actual).lub(expected, actual)
202     }
203
204     /// Computes the greatest-lower-bound, or mutual subtype, of two
205     /// values. As with `lub` order doesn't matter, except for error
206     /// cases.
207     ///
208     /// See [`At::trace`] and [`Trace::glb`] for a version of
209     /// this method that only requires `T: Relate<'tcx>`
210     pub fn glb<T>(self, expected: T, actual: T) -> InferResult<'tcx, T>
211     where
212         T: ToTrace<'tcx>,
213     {
214         self.trace(expected, actual).glb(expected, actual)
215     }
216
217     /// Sets the "trace" values that will be used for
218     /// error-reporting, but doesn't actually perform any operation
219     /// yet (this is useful when you want to set the trace using
220     /// distinct values from those you wish to operate upon).
221     pub fn trace<T>(self, expected: T, actual: T) -> Trace<'a, 'tcx>
222     where
223         T: ToTrace<'tcx>,
224     {
225         self.trace_exp(true, expected, actual)
226     }
227
228     /// Like `trace`, but the expected value is determined by the
229     /// boolean argument (if true, then the first argument `a` is the
230     /// "expected" value).
231     pub fn trace_exp<T>(self, a_is_expected: bool, a: T, b: T) -> Trace<'a, 'tcx>
232     where
233         T: ToTrace<'tcx>,
234     {
235         let trace = ToTrace::to_trace(self.infcx.tcx, self.cause, a_is_expected, a, b);
236         Trace { at: self, trace, a_is_expected }
237     }
238 }
239
240 impl<'a, 'tcx> Trace<'a, 'tcx> {
241     /// Makes `a <: b` where `a` may or may not be expected (if
242     /// `a_is_expected` is true, then `a` is expected).
243     #[instrument(skip(self), level = "debug")]
244     pub fn sub<T>(self, a: T, b: T) -> InferResult<'tcx, ()>
245     where
246         T: Relate<'tcx>,
247     {
248         let Trace { at, trace, a_is_expected } = self;
249         at.infcx.commit_if_ok(|_| {
250             let mut fields = at.infcx.combine_fields(trace, at.param_env, at.define_opaque_types);
251             fields
252                 .sub(a_is_expected)
253                 .relate(a, b)
254                 .map(move |_| InferOk { value: (), obligations: fields.obligations })
255         })
256     }
257
258     /// Makes `a == b`; the expectation is set by the call to
259     /// `trace()`.
260     #[instrument(skip(self), level = "debug")]
261     pub fn eq<T>(self, a: T, b: T) -> InferResult<'tcx, ()>
262     where
263         T: Relate<'tcx>,
264     {
265         let Trace { at, trace, a_is_expected } = self;
266         at.infcx.commit_if_ok(|_| {
267             let mut fields = at.infcx.combine_fields(trace, at.param_env, at.define_opaque_types);
268             fields
269                 .equate(a_is_expected)
270                 .relate(a, b)
271                 .map(move |_| InferOk { value: (), obligations: fields.obligations })
272         })
273     }
274
275     #[instrument(skip(self), level = "debug")]
276     pub fn lub<T>(self, a: T, b: T) -> InferResult<'tcx, T>
277     where
278         T: Relate<'tcx>,
279     {
280         let Trace { at, trace, a_is_expected } = self;
281         at.infcx.commit_if_ok(|_| {
282             let mut fields = at.infcx.combine_fields(trace, at.param_env, at.define_opaque_types);
283             fields
284                 .lub(a_is_expected)
285                 .relate(a, b)
286                 .map(move |t| InferOk { value: t, obligations: fields.obligations })
287         })
288     }
289
290     #[instrument(skip(self), level = "debug")]
291     pub fn glb<T>(self, a: T, b: T) -> InferResult<'tcx, T>
292     where
293         T: Relate<'tcx>,
294     {
295         let Trace { at, trace, a_is_expected } = self;
296         at.infcx.commit_if_ok(|_| {
297             let mut fields = at.infcx.combine_fields(trace, at.param_env, at.define_opaque_types);
298             fields
299                 .glb(a_is_expected)
300                 .relate(a, b)
301                 .map(move |t| InferOk { value: t, obligations: fields.obligations })
302         })
303     }
304 }
305
306 impl<'tcx> ToTrace<'tcx> for ImplSubject<'tcx> {
307     fn to_trace(
308         tcx: TyCtxt<'tcx>,
309         cause: &ObligationCause<'tcx>,
310         a_is_expected: bool,
311         a: Self,
312         b: Self,
313     ) -> TypeTrace<'tcx> {
314         match (a, b) {
315             (ImplSubject::Trait(trait_ref_a), ImplSubject::Trait(trait_ref_b)) => {
316                 ToTrace::to_trace(tcx, cause, a_is_expected, trait_ref_a, trait_ref_b)
317             }
318             (ImplSubject::Inherent(ty_a), ImplSubject::Inherent(ty_b)) => {
319                 ToTrace::to_trace(tcx, cause, a_is_expected, ty_a, ty_b)
320             }
321             (ImplSubject::Trait(_), ImplSubject::Inherent(_))
322             | (ImplSubject::Inherent(_), ImplSubject::Trait(_)) => {
323                 bug!("can not trace TraitRef and Ty");
324             }
325         }
326     }
327 }
328
329 impl<'tcx> ToTrace<'tcx> for Ty<'tcx> {
330     fn to_trace(
331         _: TyCtxt<'tcx>,
332         cause: &ObligationCause<'tcx>,
333         a_is_expected: bool,
334         a: Self,
335         b: Self,
336     ) -> TypeTrace<'tcx> {
337         TypeTrace {
338             cause: cause.clone(),
339             values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
340         }
341     }
342 }
343
344 impl<'tcx> ToTrace<'tcx> for ty::Region<'tcx> {
345     fn to_trace(
346         _: TyCtxt<'tcx>,
347         cause: &ObligationCause<'tcx>,
348         a_is_expected: bool,
349         a: Self,
350         b: Self,
351     ) -> TypeTrace<'tcx> {
352         TypeTrace { cause: cause.clone(), values: Regions(ExpectedFound::new(a_is_expected, a, b)) }
353     }
354 }
355
356 impl<'tcx> ToTrace<'tcx> for Const<'tcx> {
357     fn to_trace(
358         _: TyCtxt<'tcx>,
359         cause: &ObligationCause<'tcx>,
360         a_is_expected: bool,
361         a: Self,
362         b: Self,
363     ) -> TypeTrace<'tcx> {
364         TypeTrace {
365             cause: cause.clone(),
366             values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
367         }
368     }
369 }
370
371 impl<'tcx> ToTrace<'tcx> for ty::Term<'tcx> {
372     fn to_trace(
373         _: TyCtxt<'tcx>,
374         cause: &ObligationCause<'tcx>,
375         a_is_expected: bool,
376         a: Self,
377         b: Self,
378     ) -> TypeTrace<'tcx> {
379         TypeTrace { cause: cause.clone(), values: Terms(ExpectedFound::new(a_is_expected, a, b)) }
380     }
381 }
382
383 impl<'tcx> ToTrace<'tcx> for ty::TraitRef<'tcx> {
384     fn to_trace(
385         _: TyCtxt<'tcx>,
386         cause: &ObligationCause<'tcx>,
387         a_is_expected: bool,
388         a: Self,
389         b: Self,
390     ) -> TypeTrace<'tcx> {
391         TypeTrace {
392             cause: cause.clone(),
393             values: TraitRefs(ExpectedFound::new(a_is_expected, a, b)),
394         }
395     }
396 }
397
398 impl<'tcx> ToTrace<'tcx> for ty::PolyTraitRef<'tcx> {
399     fn to_trace(
400         _: TyCtxt<'tcx>,
401         cause: &ObligationCause<'tcx>,
402         a_is_expected: bool,
403         a: Self,
404         b: Self,
405     ) -> TypeTrace<'tcx> {
406         TypeTrace {
407             cause: cause.clone(),
408             values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b)),
409         }
410     }
411 }
412
413 impl<'tcx> ToTrace<'tcx> for ty::ProjectionTy<'tcx> {
414     fn to_trace(
415         tcx: TyCtxt<'tcx>,
416         cause: &ObligationCause<'tcx>,
417         a_is_expected: bool,
418         a: Self,
419         b: Self,
420     ) -> TypeTrace<'tcx> {
421         let a_ty = tcx.mk_projection(a.item_def_id, a.substs);
422         let b_ty = tcx.mk_projection(b.item_def_id, b.substs);
423         TypeTrace {
424             cause: cause.clone(),
425             values: Terms(ExpectedFound::new(a_is_expected, a_ty.into(), b_ty.into())),
426         }
427     }
428 }