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