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