]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/at.rs
Rollup merge of #102258 - cjgillot:core-kappa, r=m-ou-se
[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<'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<'tcx> InferCtxt<'tcx> {
52     #[inline]
53     pub fn at<'a>(
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             considering_regions: self.considering_regions,
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: self.tainted_by_errors.clone(),
77             err_count_on_creation: self.err_count_on_creation,
78             in_snapshot: self.in_snapshot.clone(),
79             universe: self.universe.clone(),
80             normalize_fn_sig_for_diagnostic: self
81                 .normalize_fn_sig_for_diagnostic
82                 .as_ref()
83                 .map(|f| f.clone()),
84         }
85     }
86 }
87
88 pub trait ToTrace<'tcx>: Relate<'tcx> + Copy {
89     fn to_trace(
90         tcx: TyCtxt<'tcx>,
91         cause: &ObligationCause<'tcx>,
92         a_is_expected: bool,
93         a: Self,
94         b: Self,
95     ) -> TypeTrace<'tcx>;
96 }
97
98 impl<'a, 'tcx> At<'a, 'tcx> {
99     pub fn define_opaque_types(self, define_opaque_types: bool) -> Self {
100         Self { define_opaque_types, ..self }
101     }
102
103     /// Hacky routine for equating two impl headers in coherence.
104     pub fn eq_impl_headers(
105         self,
106         expected: &ty::ImplHeader<'tcx>,
107         actual: &ty::ImplHeader<'tcx>,
108     ) -> InferResult<'tcx, ()> {
109         debug!("eq_impl_header({:?} = {:?})", expected, actual);
110         match (expected.trait_ref, actual.trait_ref) {
111             (Some(a_ref), Some(b_ref)) => self.eq(a_ref, b_ref),
112             (None, None) => self.eq(expected.self_ty, actual.self_ty),
113             _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
114         }
115     }
116
117     /// Makes `a <: b`, where `a` may or may not be expected.
118     ///
119     /// See [`At::trace_exp`] and [`Trace::sub`] for a version of
120     /// this method that only requires `T: Relate<'tcx>`
121     pub fn sub_exp<T>(self, a_is_expected: bool, a: T, b: T) -> InferResult<'tcx, ()>
122     where
123         T: ToTrace<'tcx>,
124     {
125         self.trace_exp(a_is_expected, a, b).sub(a, b)
126     }
127
128     /// Makes `actual <: expected`. For example, if type-checking a
129     /// call like `foo(x)`, where `foo: fn(i32)`, you might have
130     /// `sup(i32, x)`, since the "expected" type is the type that
131     /// appears in the signature.
132     ///
133     /// See [`At::trace`] and [`Trace::sub`] for a version of
134     /// this method that only requires `T: Relate<'tcx>`
135     pub fn sup<T>(self, expected: T, actual: T) -> InferResult<'tcx, ()>
136     where
137         T: ToTrace<'tcx>,
138     {
139         self.sub_exp(false, actual, expected)
140     }
141
142     /// Makes `expected <: actual`.
143     ///
144     /// See [`At::trace`] and [`Trace::sub`] for a version of
145     /// this method that only requires `T: Relate<'tcx>`
146     pub fn sub<T>(self, expected: T, actual: T) -> InferResult<'tcx, ()>
147     where
148         T: ToTrace<'tcx>,
149     {
150         self.sub_exp(true, expected, actual)
151     }
152
153     /// Makes `expected <: actual`.
154     ///
155     /// See [`At::trace_exp`] and [`Trace::eq`] for a version of
156     /// this method that only requires `T: Relate<'tcx>`
157     pub fn eq_exp<T>(self, a_is_expected: bool, a: T, b: T) -> InferResult<'tcx, ()>
158     where
159         T: ToTrace<'tcx>,
160     {
161         self.trace_exp(a_is_expected, a, b).eq(a, b)
162     }
163
164     /// Makes `expected <: actual`.
165     ///
166     /// See [`At::trace`] and [`Trace::eq`] for a version of
167     /// this method that only requires `T: Relate<'tcx>`
168     pub fn eq<T>(self, expected: T, actual: T) -> InferResult<'tcx, ()>
169     where
170         T: ToTrace<'tcx>,
171     {
172         self.trace(expected, actual).eq(expected, actual)
173     }
174
175     pub fn relate<T>(self, expected: T, variance: ty::Variance, actual: T) -> InferResult<'tcx, ()>
176     where
177         T: ToTrace<'tcx>,
178     {
179         match variance {
180             ty::Variance::Covariant => self.sub(expected, actual),
181             ty::Variance::Invariant => self.eq(expected, actual),
182             ty::Variance::Contravariant => self.sup(expected, actual),
183
184             // We could make this make sense but it's not readily
185             // exposed and I don't feel like dealing with it. Note
186             // that bivariance in general does a bit more than just
187             // *nothing*, it checks that the types are the same
188             // "modulo variance" basically.
189             ty::Variance::Bivariant => panic!("Bivariant given to `relate()`"),
190         }
191     }
192
193     /// Computes the least-upper-bound, or mutual supertype, of two
194     /// values. The order of the arguments doesn't matter, but since
195     /// this can result in an error (e.g., if asked to compute LUB of
196     /// u32 and i32), it is meaningful to call one of them the
197     /// "expected type".
198     ///
199     /// See [`At::trace`] and [`Trace::lub`] for a version of
200     /// this method that only requires `T: Relate<'tcx>`
201     pub fn lub<T>(self, expected: T, actual: T) -> InferResult<'tcx, T>
202     where
203         T: ToTrace<'tcx>,
204     {
205         self.trace(expected, actual).lub(expected, actual)
206     }
207
208     /// Computes the greatest-lower-bound, or mutual subtype, of two
209     /// values. As with `lub` order doesn't matter, except for error
210     /// cases.
211     ///
212     /// See [`At::trace`] and [`Trace::glb`] for a version of
213     /// this method that only requires `T: Relate<'tcx>`
214     pub fn glb<T>(self, expected: T, actual: T) -> InferResult<'tcx, T>
215     where
216         T: ToTrace<'tcx>,
217     {
218         self.trace(expected, actual).glb(expected, actual)
219     }
220
221     /// Sets the "trace" values that will be used for
222     /// error-reporting, but doesn't actually perform any operation
223     /// yet (this is useful when you want to set the trace using
224     /// distinct values from those you wish to operate upon).
225     pub fn trace<T>(self, expected: T, actual: T) -> Trace<'a, 'tcx>
226     where
227         T: ToTrace<'tcx>,
228     {
229         self.trace_exp(true, expected, actual)
230     }
231
232     /// Like `trace`, but the expected value is determined by the
233     /// boolean argument (if true, then the first argument `a` is the
234     /// "expected" value).
235     pub fn trace_exp<T>(self, a_is_expected: bool, a: T, b: T) -> Trace<'a, 'tcx>
236     where
237         T: ToTrace<'tcx>,
238     {
239         let trace = ToTrace::to_trace(self.infcx.tcx, self.cause, a_is_expected, a, b);
240         Trace { at: self, trace, a_is_expected }
241     }
242 }
243
244 impl<'a, 'tcx> Trace<'a, 'tcx> {
245     /// Makes `a <: b` where `a` may or may not be expected (if
246     /// `a_is_expected` is true, then `a` is expected).
247     #[instrument(skip(self), level = "debug")]
248     pub fn sub<T>(self, a: T, b: T) -> InferResult<'tcx, ()>
249     where
250         T: Relate<'tcx>,
251     {
252         let Trace { at, trace, a_is_expected } = self;
253         at.infcx.commit_if_ok(|_| {
254             let mut fields = at.infcx.combine_fields(trace, at.param_env, at.define_opaque_types);
255             fields
256                 .sub(a_is_expected)
257                 .relate(a, b)
258                 .map(move |_| InferOk { value: (), obligations: fields.obligations })
259         })
260     }
261
262     /// Makes `a == b`; the expectation is set by the call to
263     /// `trace()`.
264     #[instrument(skip(self), level = "debug")]
265     pub fn eq<T>(self, a: T, b: T) -> InferResult<'tcx, ()>
266     where
267         T: Relate<'tcx>,
268     {
269         let Trace { at, trace, a_is_expected } = self;
270         at.infcx.commit_if_ok(|_| {
271             let mut fields = at.infcx.combine_fields(trace, at.param_env, at.define_opaque_types);
272             fields
273                 .equate(a_is_expected)
274                 .relate(a, b)
275                 .map(move |_| InferOk { value: (), obligations: fields.obligations })
276         })
277     }
278
279     #[instrument(skip(self), level = "debug")]
280     pub fn lub<T>(self, a: T, b: T) -> InferResult<'tcx, T>
281     where
282         T: Relate<'tcx>,
283     {
284         let Trace { at, trace, a_is_expected } = self;
285         at.infcx.commit_if_ok(|_| {
286             let mut fields = at.infcx.combine_fields(trace, at.param_env, at.define_opaque_types);
287             fields
288                 .lub(a_is_expected)
289                 .relate(a, b)
290                 .map(move |t| InferOk { value: t, obligations: fields.obligations })
291         })
292     }
293
294     #[instrument(skip(self), level = "debug")]
295     pub fn glb<T>(self, a: T, b: T) -> InferResult<'tcx, T>
296     where
297         T: Relate<'tcx>,
298     {
299         let Trace { at, trace, a_is_expected } = self;
300         at.infcx.commit_if_ok(|_| {
301             let mut fields = at.infcx.combine_fields(trace, at.param_env, at.define_opaque_types);
302             fields
303                 .glb(a_is_expected)
304                 .relate(a, b)
305                 .map(move |t| InferOk { value: t, obligations: fields.obligations })
306         })
307     }
308 }
309
310 impl<'tcx> ToTrace<'tcx> for ImplSubject<'tcx> {
311     fn to_trace(
312         tcx: TyCtxt<'tcx>,
313         cause: &ObligationCause<'tcx>,
314         a_is_expected: bool,
315         a: Self,
316         b: Self,
317     ) -> TypeTrace<'tcx> {
318         match (a, b) {
319             (ImplSubject::Trait(trait_ref_a), ImplSubject::Trait(trait_ref_b)) => {
320                 ToTrace::to_trace(tcx, cause, a_is_expected, trait_ref_a, trait_ref_b)
321             }
322             (ImplSubject::Inherent(ty_a), ImplSubject::Inherent(ty_b)) => {
323                 ToTrace::to_trace(tcx, cause, a_is_expected, ty_a, ty_b)
324             }
325             (ImplSubject::Trait(_), ImplSubject::Inherent(_))
326             | (ImplSubject::Inherent(_), ImplSubject::Trait(_)) => {
327                 bug!("can not trace TraitRef and Ty");
328             }
329         }
330     }
331 }
332
333 impl<'tcx> ToTrace<'tcx> for Ty<'tcx> {
334     fn to_trace(
335         _: TyCtxt<'tcx>,
336         cause: &ObligationCause<'tcx>,
337         a_is_expected: bool,
338         a: Self,
339         b: Self,
340     ) -> TypeTrace<'tcx> {
341         TypeTrace {
342             cause: cause.clone(),
343             values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
344         }
345     }
346 }
347
348 impl<'tcx> ToTrace<'tcx> for ty::Region<'tcx> {
349     fn to_trace(
350         _: TyCtxt<'tcx>,
351         cause: &ObligationCause<'tcx>,
352         a_is_expected: bool,
353         a: Self,
354         b: Self,
355     ) -> TypeTrace<'tcx> {
356         TypeTrace { cause: cause.clone(), values: Regions(ExpectedFound::new(a_is_expected, a, b)) }
357     }
358 }
359
360 impl<'tcx> ToTrace<'tcx> for Const<'tcx> {
361     fn to_trace(
362         _: TyCtxt<'tcx>,
363         cause: &ObligationCause<'tcx>,
364         a_is_expected: bool,
365         a: Self,
366         b: Self,
367     ) -> TypeTrace<'tcx> {
368         TypeTrace {
369             cause: cause.clone(),
370             values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
371         }
372     }
373 }
374
375 impl<'tcx> ToTrace<'tcx> for ty::Term<'tcx> {
376     fn to_trace(
377         _: TyCtxt<'tcx>,
378         cause: &ObligationCause<'tcx>,
379         a_is_expected: bool,
380         a: Self,
381         b: Self,
382     ) -> TypeTrace<'tcx> {
383         TypeTrace { cause: cause.clone(), values: Terms(ExpectedFound::new(a_is_expected, a, b)) }
384     }
385 }
386
387 impl<'tcx> ToTrace<'tcx> for ty::TraitRef<'tcx> {
388     fn to_trace(
389         _: TyCtxt<'tcx>,
390         cause: &ObligationCause<'tcx>,
391         a_is_expected: bool,
392         a: Self,
393         b: Self,
394     ) -> TypeTrace<'tcx> {
395         TypeTrace {
396             cause: cause.clone(),
397             values: TraitRefs(ExpectedFound::new(a_is_expected, a, b)),
398         }
399     }
400 }
401
402 impl<'tcx> ToTrace<'tcx> for ty::PolyTraitRef<'tcx> {
403     fn to_trace(
404         _: TyCtxt<'tcx>,
405         cause: &ObligationCause<'tcx>,
406         a_is_expected: bool,
407         a: Self,
408         b: Self,
409     ) -> TypeTrace<'tcx> {
410         TypeTrace {
411             cause: cause.clone(),
412             values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b)),
413         }
414     }
415 }
416
417 impl<'tcx> ToTrace<'tcx> for ty::ProjectionTy<'tcx> {
418     fn to_trace(
419         tcx: TyCtxt<'tcx>,
420         cause: &ObligationCause<'tcx>,
421         a_is_expected: bool,
422         a: Self,
423         b: Self,
424     ) -> TypeTrace<'tcx> {
425         let a_ty = tcx.mk_projection(a.item_def_id, a.substs);
426         let b_ty = tcx.mk_projection(b.item_def_id, b.substs);
427         TypeTrace {
428             cause: cause.clone(),
429             values: Terms(ExpectedFound::new(a_is_expected, a_ty.into(), b_ty.into())),
430         }
431     }
432 }