1 use crate::ty::{self, Ty, TyCtxt, InferConst};
2 use crate::ty::error::TypeError;
3 use crate::ty::relate::{self, Relate, TypeRelation, RelateResult};
4 use crate::mir::interpret::ConstValue;
6 /// A type "A" *matches* "B" if the fresh types in B could be
7 /// substituted with values so as to make it equal to A. Matching is
8 /// intended to be used only on freshened types, and it basically
9 /// indicates if the non-freshened versions of A and B could have been
12 /// It is only an approximation. If it yields false, unification would
13 /// definitely fail, but a true result doesn't mean unification would
14 /// succeed. This is because we don't track the "side-constraints" on
15 /// type variables, nor do we track if the same freshened type appears
16 /// more than once. To some extent these approximations could be
17 /// fixed, given effort.
19 /// Like subtyping, matching is really a binary relation, so the only
20 /// important thing about the result is Ok/Err. Also, matching never
21 /// affects any type variables or unification state.
22 pub struct Match<'gcx, 'tcx> {
23 tcx: TyCtxt<'gcx, 'tcx>,
26 impl Match<'gcx, 'tcx> {
27 pub fn new(tcx: TyCtxt<'gcx, 'tcx>) -> Match<'gcx, 'tcx> {
32 impl TypeRelation<'gcx, 'tcx> for Match<'gcx, 'tcx> {
33 fn tag(&self) -> &'static str { "Match" }
34 fn tcx(&self) -> TyCtxt<'gcx, 'tcx> { self.tcx }
35 fn a_is_expected(&self) -> bool { true } // irrelevant
37 fn relate_with_variance<T: Relate<'tcx>>(&mut self,
41 -> RelateResult<'tcx, T>
46 fn regions(&mut self, a: ty::Region<'tcx>, b: ty::Region<'tcx>)
47 -> RelateResult<'tcx, ty::Region<'tcx>> {
48 debug!("{}.regions({:?}, {:?})",
55 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
56 debug!("{}.tys({:?}, {:?})", self.tag(),
58 if a == b { return Ok(a); }
60 match (&a.sty, &b.sty) {
61 (_, &ty::Infer(ty::FreshTy(_))) |
62 (_, &ty::Infer(ty::FreshIntTy(_))) |
63 (_, &ty::Infer(ty::FreshFloatTy(_))) => {
68 (_, &ty::Infer(_)) => {
69 Err(TypeError::Sorts(relate::expected_found(self, &a, &b)))
72 (&ty::Error, _) | (_, &ty::Error) => {
73 Ok(self.tcx().types.err)
77 relate::super_relate_tys(self, a, b)
84 a: &'tcx ty::Const<'tcx>,
85 b: &'tcx ty::Const<'tcx>,
86 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
87 debug!("{}.consts({:?}, {:?})", self.tag(), a, b);
92 match (a.val, b.val) {
93 (_, ConstValue::Infer(InferConst::Fresh(_))) => {
97 (ConstValue::Infer(_), _) | (_, ConstValue::Infer(_)) => {
98 return Err(TypeError::ConstMismatch(relate::expected_found(self, &a, &b)));
104 relate::super_relate_consts(self, a, b)
107 fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
108 -> RelateResult<'tcx, ty::Binder<T>>
109 where T: Relate<'tcx>
111 Ok(ty::Binder::bind(self.relate(a.skip_binder(), b.skip_binder())?))