]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/combine.rs
Auto merge of #58953 - jethrogb:jb/unify-ffi, r=alexcrichton
[rust.git] / src / librustc / infer / combine.rs
1 ///////////////////////////////////////////////////////////////////////////
2 // # Type combining
3 //
4 // There are four type combiners: equate, sub, lub, and glb.  Each
5 // implements the trait `Combine` and contains methods for combining
6 // two instances of various things and yielding a new instance.  These
7 // combiner methods always yield a `Result<T>`.  There is a lot of
8 // common code for these operations, implemented as default methods on
9 // the `Combine` trait.
10 //
11 // Each operation may have side-effects on the inference context,
12 // though these can be unrolled using snapshots. On success, the
13 // LUB/GLB operations return the appropriate bound. The Eq and Sub
14 // operations generally return the first operand.
15 //
16 // ## Contravariance
17 //
18 // When you are relating two things which have a contravariant
19 // relationship, you should use `contratys()` or `contraregions()`,
20 // rather than inversing the order of arguments!  This is necessary
21 // because the order of arguments is not relevant for LUB and GLB.  It
22 // is also useful to track which value is the "expected" value in
23 // terms of error reporting.
24
25 use super::equate::Equate;
26 use super::glb::Glb;
27 use super::{InferCtxt, MiscVariable, TypeTrace};
28 use super::lub::Lub;
29 use super::sub::Sub;
30 use super::type_variable::TypeVariableValue;
31
32 use crate::hir::def_id::DefId;
33 use crate::ty::{IntType, UintType};
34 use crate::ty::{self, Ty, TyCtxt};
35 use crate::ty::error::TypeError;
36 use crate::ty::relate::{self, Relate, RelateResult, TypeRelation};
37 use crate::ty::subst::SubstsRef;
38 use crate::traits::{Obligation, PredicateObligations};
39
40 use syntax::ast;
41 use syntax_pos::Span;
42
43 #[derive(Clone)]
44 pub struct CombineFields<'infcx, 'gcx: 'infcx+'tcx, 'tcx: 'infcx> {
45     pub infcx: &'infcx InferCtxt<'infcx, 'gcx, 'tcx>,
46     pub trace: TypeTrace<'tcx>,
47     pub cause: Option<ty::relate::Cause>,
48     pub param_env: ty::ParamEnv<'tcx>,
49     pub obligations: PredicateObligations<'tcx>,
50 }
51
52 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
53 pub enum RelationDir {
54     SubtypeOf, SupertypeOf, EqTo
55 }
56
57 impl<'infcx, 'gcx, 'tcx> InferCtxt<'infcx, 'gcx, 'tcx> {
58     pub fn super_combine_tys<R>(&self,
59                                 relation: &mut R,
60                                 a: Ty<'tcx>,
61                                 b: Ty<'tcx>)
62                                 -> RelateResult<'tcx, Ty<'tcx>>
63         where R: TypeRelation<'infcx, 'gcx, 'tcx>
64     {
65         let a_is_expected = relation.a_is_expected();
66
67         match (&a.sty, &b.sty) {
68             // Relate integral variables to other types
69             (&ty::Infer(ty::IntVar(a_id)), &ty::Infer(ty::IntVar(b_id))) => {
70                 self.int_unification_table
71                     .borrow_mut()
72                     .unify_var_var(a_id, b_id)
73                     .map_err(|e| int_unification_error(a_is_expected, e))?;
74                 Ok(a)
75             }
76             (&ty::Infer(ty::IntVar(v_id)), &ty::Int(v)) => {
77                 self.unify_integral_variable(a_is_expected, v_id, IntType(v))
78             }
79             (&ty::Int(v), &ty::Infer(ty::IntVar(v_id))) => {
80                 self.unify_integral_variable(!a_is_expected, v_id, IntType(v))
81             }
82             (&ty::Infer(ty::IntVar(v_id)), &ty::Uint(v)) => {
83                 self.unify_integral_variable(a_is_expected, v_id, UintType(v))
84             }
85             (&ty::Uint(v), &ty::Infer(ty::IntVar(v_id))) => {
86                 self.unify_integral_variable(!a_is_expected, v_id, UintType(v))
87             }
88
89             // Relate floating-point variables to other types
90             (&ty::Infer(ty::FloatVar(a_id)), &ty::Infer(ty::FloatVar(b_id))) => {
91                 self.float_unification_table
92                     .borrow_mut()
93                     .unify_var_var(a_id, b_id)
94                     .map_err(|e| float_unification_error(relation.a_is_expected(), e))?;
95                 Ok(a)
96             }
97             (&ty::Infer(ty::FloatVar(v_id)), &ty::Float(v)) => {
98                 self.unify_float_variable(a_is_expected, v_id, v)
99             }
100             (&ty::Float(v), &ty::Infer(ty::FloatVar(v_id))) => {
101                 self.unify_float_variable(!a_is_expected, v_id, v)
102             }
103
104             // All other cases of inference are errors
105             (&ty::Infer(_), _) |
106             (_, &ty::Infer(_)) => {
107                 Err(TypeError::Sorts(ty::relate::expected_found(relation, &a, &b)))
108             }
109
110
111             _ => {
112                 ty::relate::super_relate_tys(relation, a, b)
113             }
114         }
115     }
116
117     fn unify_integral_variable(&self,
118                                vid_is_expected: bool,
119                                vid: ty::IntVid,
120                                val: ty::IntVarValue)
121                                -> RelateResult<'tcx, Ty<'tcx>>
122     {
123         self.int_unification_table
124             .borrow_mut()
125             .unify_var_value(vid, Some(val))
126             .map_err(|e| int_unification_error(vid_is_expected, e))?;
127         match val {
128             IntType(v) => Ok(self.tcx.mk_mach_int(v)),
129             UintType(v) => Ok(self.tcx.mk_mach_uint(v)),
130         }
131     }
132
133     fn unify_float_variable(&self,
134                             vid_is_expected: bool,
135                             vid: ty::FloatVid,
136                             val: ast::FloatTy)
137                             -> RelateResult<'tcx, Ty<'tcx>>
138     {
139         self.float_unification_table
140             .borrow_mut()
141             .unify_var_value(vid, Some(ty::FloatVarValue(val)))
142             .map_err(|e| float_unification_error(vid_is_expected, e))?;
143         Ok(self.tcx.mk_mach_float(val))
144     }
145 }
146
147 impl<'infcx, 'gcx, 'tcx> CombineFields<'infcx, 'gcx, 'tcx> {
148     pub fn tcx(&self) -> TyCtxt<'infcx, 'gcx, 'tcx> {
149         self.infcx.tcx
150     }
151
152     pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'gcx, 'tcx> {
153         Equate::new(self, a_is_expected)
154     }
155
156     pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'gcx, 'tcx> {
157         Sub::new(self, a_is_expected)
158     }
159
160     pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'gcx, 'tcx> {
161         Lub::new(self, a_is_expected)
162     }
163
164     pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'gcx, 'tcx> {
165         Glb::new(self, a_is_expected)
166     }
167
168     /// Here, `dir` is either `EqTo`, `SubtypeOf`, or `SupertypeOf`.
169     /// The idea is that we should ensure that the type `a_ty` is equal
170     /// to, a subtype of, or a supertype of (respectively) the type
171     /// to which `b_vid` is bound.
172     ///
173     /// Since `b_vid` has not yet been instantiated with a type, we
174     /// will first instantiate `b_vid` with a *generalized* version
175     /// of `a_ty`. Generalization introduces other inference
176     /// variables wherever subtyping could occur.
177     pub fn instantiate(&mut self,
178                        a_ty: Ty<'tcx>,
179                        dir: RelationDir,
180                        b_vid: ty::TyVid,
181                        a_is_expected: bool)
182                        -> RelateResult<'tcx, ()>
183     {
184         use self::RelationDir::*;
185
186         // Get the actual variable that b_vid has been inferred to
187         debug_assert!(self.infcx.type_variables.borrow_mut().probe(b_vid).is_unknown());
188
189         debug!("instantiate(a_ty={:?} dir={:?} b_vid={:?})", a_ty, dir, b_vid);
190
191         // Generalize type of `a_ty` appropriately depending on the
192         // direction.  As an example, assume:
193         //
194         // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an
195         //   inference variable,
196         // - and `dir` == `SubtypeOf`.
197         //
198         // Then the generalized form `b_ty` would be `&'?2 ?3`, where
199         // `'?2` and `?3` are fresh region/type inference
200         // variables. (Down below, we will relate `a_ty <: b_ty`,
201         // adding constraints like `'x: '?2` and `?1 <: ?3`.)
202         let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?;
203         debug!("instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})",
204                a_ty, dir, b_vid, b_ty);
205         self.infcx.type_variables.borrow_mut().instantiate(b_vid, b_ty);
206
207         if needs_wf {
208             self.obligations.push(Obligation::new(self.trace.cause.clone(),
209                                                   self.param_env,
210                                                   ty::Predicate::WellFormed(b_ty)));
211         }
212
213         // Finally, relate `b_ty` to `a_ty`, as described in previous comment.
214         //
215         // FIXME(#16847): This code is non-ideal because all these subtype
216         // relations wind up attributed to the same spans. We need
217         // to associate causes/spans with each of the relations in
218         // the stack to get this right.
219         match dir {
220             EqTo => self.equate(a_is_expected).relate(&a_ty, &b_ty),
221             SubtypeOf => self.sub(a_is_expected).relate(&a_ty, &b_ty),
222             SupertypeOf => self.sub(a_is_expected).relate_with_variance(
223                 ty::Contravariant, &a_ty, &b_ty),
224         }?;
225
226         Ok(())
227     }
228
229     /// Attempts to generalize `ty` for the type variable `for_vid`.
230     /// This checks for cycle -- that is, whether the type `ty`
231     /// references `for_vid`. The `dir` is the "direction" for which we
232     /// a performing the generalization (i.e., are we producing a type
233     /// that can be used as a supertype etc).
234     ///
235     /// Preconditions:
236     ///
237     /// - `for_vid` is a "root vid"
238     fn generalize(&self,
239                   ty: Ty<'tcx>,
240                   for_vid: ty::TyVid,
241                   dir: RelationDir)
242                   -> RelateResult<'tcx, Generalization<'tcx>>
243     {
244         debug!("generalize(ty={:?}, for_vid={:?}, dir={:?}", ty, for_vid, dir);
245         // Determine the ambient variance within which `ty` appears.
246         // The surrounding equation is:
247         //
248         //     ty [op] ty2
249         //
250         // where `op` is either `==`, `<:`, or `:>`. This maps quite
251         // naturally.
252         let ambient_variance = match dir {
253             RelationDir::EqTo => ty::Invariant,
254             RelationDir::SubtypeOf => ty::Covariant,
255             RelationDir::SupertypeOf => ty::Contravariant,
256         };
257
258         debug!("generalize: ambient_variance = {:?}", ambient_variance);
259
260         let for_universe = match self.infcx.type_variables.borrow_mut().probe(for_vid) {
261             v @ TypeVariableValue::Known { .. } => panic!(
262                 "instantiating {:?} which has a known value {:?}",
263                 for_vid,
264                 v,
265             ),
266             TypeVariableValue::Unknown { universe } => universe,
267         };
268
269         debug!("generalize: for_universe = {:?}", for_universe);
270
271         let mut generalize = Generalizer {
272             infcx: self.infcx,
273             span: self.trace.cause.span,
274             for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
275             for_universe,
276             ambient_variance,
277             needs_wf: false,
278             root_ty: ty,
279         };
280
281         let ty = match generalize.relate(&ty, &ty) {
282             Ok(ty) => ty,
283             Err(e) => {
284                 debug!("generalize: failure {:?}", e);
285                 return Err(e);
286             }
287         };
288         let needs_wf = generalize.needs_wf;
289         debug!("generalize: success {{ {:?}, {:?} }}", ty, needs_wf);
290         Ok(Generalization { ty, needs_wf })
291     }
292 }
293
294 struct Generalizer<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
295     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
296
297     /// The span, used when creating new type variables and things.
298     span: Span,
299
300     /// The vid of the type variable that is in the process of being
301     /// instantiated; if we find this within the type we are folding,
302     /// that means we would have created a cyclic type.
303     for_vid_sub_root: ty::TyVid,
304
305     /// The universe of the type variable that is in the process of
306     /// being instantiated. Any fresh variables that we create in this
307     /// process should be in that same universe.
308     for_universe: ty::UniverseIndex,
309
310     /// Track the variance as we descend into the type.
311     ambient_variance: ty::Variance,
312
313     /// See the field `needs_wf` in `Generalization`.
314     needs_wf: bool,
315
316     /// The root type that we are generalizing. Used when reporting cycles.
317     root_ty: Ty<'tcx>,
318 }
319
320 /// Result from a generalization operation. This includes
321 /// not only the generalized type, but also a bool flag
322 /// indicating whether further WF checks are needed.
323 struct Generalization<'tcx> {
324     ty: Ty<'tcx>,
325
326     /// If true, then the generalized type may not be well-formed,
327     /// even if the source type is well-formed, so we should add an
328     /// additional check to enforce that it is. This arises in
329     /// particular around 'bivariant' type parameters that are only
330     /// constrained by a where-clause. As an example, imagine a type:
331     ///
332     ///     struct Foo<A, B> where A: Iterator<Item = B> {
333     ///         data: A
334     ///     }
335     ///
336     /// here, `A` will be covariant, but `B` is
337     /// unconstrained. However, whatever it is, for `Foo` to be WF, it
338     /// must be equal to `A::Item`. If we have an input `Foo<?A, ?B>`,
339     /// then after generalization we will wind up with a type like
340     /// `Foo<?C, ?D>`. When we enforce that `Foo<?A, ?B> <: Foo<?C,
341     /// ?D>` (or `>:`), we will wind up with the requirement that `?A
342     /// <: ?C`, but no particular relationship between `?B` and `?D`
343     /// (after all, we do not know the variance of the normalized form
344     /// of `A::Item` with respect to `A`). If we do nothing else, this
345     /// may mean that `?D` goes unconstrained (as in #41677). So, in
346     /// this scenario where we create a new type variable in a
347     /// bivariant context, we set the `needs_wf` flag to true. This
348     /// will force the calling code to check that `WF(Foo<?C, ?D>)`
349     /// holds, which in turn implies that `?C::Item == ?D`. So once
350     /// `?C` is constrained, that should suffice to restrict `?D`.
351     needs_wf: bool,
352 }
353
354 impl<'cx, 'gcx, 'tcx> TypeRelation<'cx, 'gcx, 'tcx> for Generalizer<'cx, 'gcx, 'tcx> {
355     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
356         self.infcx.tcx
357     }
358
359     fn tag(&self) -> &'static str {
360         "Generalizer"
361     }
362
363     fn a_is_expected(&self) -> bool {
364         true
365     }
366
367     fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
368                   -> RelateResult<'tcx, ty::Binder<T>>
369         where T: Relate<'tcx>
370     {
371         Ok(ty::Binder::bind(self.relate(a.skip_binder(), b.skip_binder())?))
372     }
373
374     fn relate_item_substs(&mut self,
375                           item_def_id: DefId,
376                           a_subst: SubstsRef<'tcx>,
377                           b_subst: SubstsRef<'tcx>)
378                           -> RelateResult<'tcx, SubstsRef<'tcx>>
379     {
380         if self.ambient_variance == ty::Variance::Invariant {
381             // Avoid fetching the variance if we are in an invariant
382             // context; no need, and it can induce dependency cycles
383             // (e.g., #41849).
384             relate::relate_substs(self, None, a_subst, b_subst)
385         } else {
386             let opt_variances = self.tcx().variances_of(item_def_id);
387             relate::relate_substs(self, Some(&opt_variances), a_subst, b_subst)
388         }
389     }
390
391     fn relate_with_variance<T: Relate<'tcx>>(&mut self,
392                                              variance: ty::Variance,
393                                              a: &T,
394                                              b: &T)
395                                              -> RelateResult<'tcx, T>
396     {
397         let old_ambient_variance = self.ambient_variance;
398         self.ambient_variance = self.ambient_variance.xform(variance);
399
400         let result = self.relate(a, b);
401         self.ambient_variance = old_ambient_variance;
402         result
403     }
404
405     fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
406         assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
407
408         debug!("generalize: t={:?}", t);
409
410         // Check to see whether the type we are genealizing references
411         // any other type variable related to `vid` via
412         // subtyping. This is basically our "occurs check", preventing
413         // us from creating infinitely sized types.
414         match t.sty {
415             ty::Infer(ty::TyVar(vid)) => {
416                 let mut variables = self.infcx.type_variables.borrow_mut();
417                 let vid = variables.root_var(vid);
418                 let sub_vid = variables.sub_root_var(vid);
419                 if sub_vid == self.for_vid_sub_root {
420                     // If sub-roots are equal, then `for_vid` and
421                     // `vid` are related via subtyping.
422                     return Err(TypeError::CyclicTy(self.root_ty));
423                 } else {
424                     match variables.probe(vid) {
425                         TypeVariableValue::Known { value: u } => {
426                             drop(variables);
427                             debug!("generalize: known value {:?}", u);
428                             self.relate(&u, &u)
429                         }
430                         TypeVariableValue::Unknown { universe } => {
431                             match self.ambient_variance {
432                                 // Invariant: no need to make a fresh type variable.
433                                 ty::Invariant => {
434                                     if self.for_universe.can_name(universe) {
435                                         return Ok(t);
436                                     }
437                                 }
438
439                                 // Bivariant: make a fresh var, but we
440                                 // may need a WF predicate. See
441                                 // comment on `needs_wf` field for
442                                 // more info.
443                                 ty::Bivariant => self.needs_wf = true,
444
445                                 // Co/contravariant: this will be
446                                 // sufficiently constrained later on.
447                                 ty::Covariant | ty::Contravariant => (),
448                             }
449
450                             let origin = *variables.var_origin(vid);
451                             let new_var_id = variables.new_var(self.for_universe, false, origin);
452                             let u = self.tcx().mk_ty_var(new_var_id);
453                             debug!("generalize: replacing original vid={:?} with new={:?}",
454                                    vid, u);
455                             return Ok(u);
456                         }
457                     }
458                 }
459             }
460             ty::Infer(ty::IntVar(_)) |
461             ty::Infer(ty::FloatVar(_)) => {
462                 // No matter what mode we are in,
463                 // integer/floating-point types must be equal to be
464                 // relatable.
465                 Ok(t)
466             }
467             _ => {
468                 relate::super_relate_tys(self, t, t)
469             }
470         }
471     }
472
473     fn regions(&mut self, r: ty::Region<'tcx>, r2: ty::Region<'tcx>)
474                -> RelateResult<'tcx, ty::Region<'tcx>> {
475         assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be ==
476
477         debug!("generalize: regions r={:?}", r);
478
479         match *r {
480             // Never make variables for regions bound within the type itself,
481             // nor for erased regions.
482             ty::ReLateBound(..) |
483             ty::ReErased => {
484                 return Ok(r);
485             }
486
487             ty::ReClosureBound(..) => {
488                 span_bug!(
489                     self.span,
490                     "encountered unexpected ReClosureBound: {:?}",
491                     r,
492                 );
493             }
494
495             ty::RePlaceholder(..) |
496             ty::ReVar(..) |
497             ty::ReEmpty |
498             ty::ReStatic |
499             ty::ReScope(..) |
500             ty::ReEarlyBound(..) |
501             ty::ReFree(..) => {
502                 // see common code below
503             }
504         }
505
506         // If we are in an invariant context, we can re-use the region
507         // as is, unless it happens to be in some universe that we
508         // can't name. (In the case of a region *variable*, we could
509         // use it if we promoted it into our universe, but we don't
510         // bother.)
511         if let ty::Invariant = self.ambient_variance {
512             let r_universe = self.infcx.universe_of_region(r);
513             if self.for_universe.can_name(r_universe) {
514                 return Ok(r);
515             }
516         }
517
518         // FIXME: This is non-ideal because we don't give a
519         // very descriptive origin for this region variable.
520         Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe))
521     }
522 }
523
524 pub trait RelateResultCompare<'tcx, T> {
525     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
526         F: FnOnce() -> TypeError<'tcx>;
527 }
528
529 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
530     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
531         F: FnOnce() -> TypeError<'tcx>,
532     {
533         self.clone().and_then(|s| {
534             if s == t {
535                 self.clone()
536             } else {
537                 Err(f())
538             }
539         })
540     }
541 }
542
543 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
544                                -> TypeError<'tcx>
545 {
546     let (a, b) = v;
547     TypeError::IntMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
548 }
549
550 fn float_unification_error<'tcx>(a_is_expected: bool,
551                                  v: (ty::FloatVarValue, ty::FloatVarValue))
552                                  -> TypeError<'tcx>
553 {
554     let (ty::FloatVarValue(a), ty::FloatVarValue(b)) = v;
555     TypeError::FloatMismatch(ty::relate::expected_found_bool(a_is_expected, &a, &b))
556 }