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