]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/lattice.rs
Merge commit 'd3a2366ee877075c59b38bd8ced55f224fc7ef51' into sync_cg_clif-2022-07-26
[rust.git] / compiler / rustc_infer / src / infer / lattice.rs
1 //! # Lattice variables
2 //!
3 //! Generic code for operating on [lattices] of inference variables
4 //! that are characterized by an upper- and lower-bound.
5 //!
6 //! The code is defined quite generically so that it can be
7 //! applied both to type variables, which represent types being inferred,
8 //! and fn variables, which represent function types being inferred.
9 //! (It may eventually be applied to their types as well.)
10 //! In some cases, the functions are also generic with respect to the
11 //! operation on the lattice (GLB vs LUB).
12 //!
13 //! ## Note
14 //!
15 //! Although all the functions are generic, for simplicity, comments in the source code
16 //! generally refer to type variables and the LUB operation.
17 //!
18 //! [lattices]: https://en.wikipedia.org/wiki/Lattice_(order)
19
20 use super::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
21 use super::InferCtxt;
22
23 use crate::traits::{ObligationCause, PredicateObligation};
24 use rustc_middle::ty::relate::{RelateResult, TypeRelation};
25 use rustc_middle::ty::TyVar;
26 use rustc_middle::ty::{self, Ty};
27
28 /// Trait for returning data about a lattice, and for abstracting
29 /// over the "direction" of the lattice operation (LUB/GLB).
30 ///
31 /// GLB moves "down" the lattice (to smaller values); LUB moves
32 /// "up" the lattice (to bigger values).
33 pub trait LatticeDir<'f, 'tcx>: TypeRelation<'tcx> {
34     fn infcx(&self) -> &'f InferCtxt<'f, 'tcx>;
35
36     fn cause(&self) -> &ObligationCause<'tcx>;
37
38     fn add_obligations(&mut self, obligations: Vec<PredicateObligation<'tcx>>);
39
40     fn define_opaque_types(&self) -> bool;
41
42     // Relates the type `v` to `a` and `b` such that `v` represents
43     // the LUB/GLB of `a` and `b` as appropriate.
44     //
45     // Subtle hack: ordering *may* be significant here. This method
46     // relates `v` to `a` first, which may help us to avoid unnecessary
47     // type variable obligations. See caller for details.
48     fn relate_bound(&mut self, v: Ty<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()>;
49 }
50
51 /// Relates two types using a given lattice.
52 #[instrument(skip(this), level = "debug")]
53 pub fn super_lattice_tys<'a, 'tcx: 'a, L>(
54     this: &mut L,
55     a: Ty<'tcx>,
56     b: Ty<'tcx>,
57 ) -> RelateResult<'tcx, Ty<'tcx>>
58 where
59     L: LatticeDir<'a, 'tcx>,
60 {
61     debug!("{}", this.tag());
62
63     if a == b {
64         return Ok(a);
65     }
66
67     let infcx = this.infcx();
68
69     let a = infcx.inner.borrow_mut().type_variables().replace_if_possible(a);
70     let b = infcx.inner.borrow_mut().type_variables().replace_if_possible(b);
71
72     match (a.kind(), b.kind()) {
73         // If one side is known to be a variable and one is not,
74         // create a variable (`v`) to represent the LUB. Make sure to
75         // relate `v` to the non-type-variable first (by passing it
76         // first to `relate_bound`). Otherwise, we would produce a
77         // subtype obligation that must then be processed.
78         //
79         // Example: if the LHS is a type variable, and RHS is
80         // `Box<i32>`, then we current compare `v` to the RHS first,
81         // which will instantiate `v` with `Box<i32>`.  Then when `v`
82         // is compared to the LHS, we instantiate LHS with `Box<i32>`.
83         // But if we did in reverse order, we would create a `v <:
84         // LHS` (or vice versa) constraint and then instantiate
85         // `v`. This would require further processing to achieve same
86         // end-result; in particular, this screws up some of the logic
87         // in coercion, which expects LUB to figure out that the LHS
88         // is (e.g.) `Box<i32>`. A more obvious solution might be to
89         // iterate on the subtype obligations that are returned, but I
90         // think this suffices. -nmatsakis
91         (&ty::Infer(TyVar(..)), _) => {
92             let v = infcx.next_ty_var(TypeVariableOrigin {
93                 kind: TypeVariableOriginKind::LatticeVariable,
94                 span: this.cause().span,
95             });
96             this.relate_bound(v, b, a)?;
97             Ok(v)
98         }
99         (_, &ty::Infer(TyVar(..))) => {
100             let v = infcx.next_ty_var(TypeVariableOrigin {
101                 kind: TypeVariableOriginKind::LatticeVariable,
102                 span: this.cause().span,
103             });
104             this.relate_bound(v, a, b)?;
105             Ok(v)
106         }
107
108         (&ty::Opaque(a_def_id, _), &ty::Opaque(b_def_id, _)) if a_def_id == b_def_id => {
109             infcx.super_combine_tys(this, a, b)
110         }
111         (&ty::Opaque(did, ..), _) | (_, &ty::Opaque(did, ..))
112             if this.define_opaque_types() && did.is_local() =>
113         {
114             this.add_obligations(
115                 infcx
116                     .handle_opaque_type(a, b, this.a_is_expected(), this.cause(), this.param_env())?
117                     .obligations,
118             );
119             Ok(a)
120         }
121
122         _ => infcx.super_combine_tys(this, a, b),
123     }
124 }