1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use ty::{self, Ty, TyCtxt};
12 use ty::error::TypeError;
13 use ty::relate::{self, Relate, TypeRelation, RelateResult};
15 /// A type "A" *matches* "B" if the fresh types in B could be
16 /// substituted with values so as to make it equal to A. Matching is
17 /// intended to be used only on freshened types, and it basically
18 /// indicates if the non-freshened versions of A and B could have been
21 /// It is only an approximation. If it yields false, unification would
22 /// definitely fail, but a true result doesn't mean unification would
23 /// succeed. This is because we don't track the "side-constraints" on
24 /// type variables, nor do we track if the same freshened type appears
25 /// more than once. To some extent these approximations could be
26 /// fixed, given effort.
28 /// Like subtyping, matching is really a binary relation, so the only
29 /// important thing about the result is Ok/Err. Also, matching never
30 /// affects any type variables or unification state.
31 pub struct Match<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
32 tcx: TyCtxt<'a, 'gcx, 'tcx>
35 impl<'a, 'gcx, 'tcx> Match<'a, 'gcx, 'tcx> {
36 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Match<'a, 'gcx, 'tcx> {
41 impl<'a, 'gcx, 'tcx> TypeRelation<'a, 'gcx, 'tcx> for Match<'a, 'gcx, 'tcx> {
42 fn tag(&self) -> &'static str { "Match" }
43 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> { self.tcx }
44 fn a_is_expected(&self) -> bool { true } // irrelevant
46 fn relate_with_variance<T: Relate<'tcx>>(&mut self,
50 -> RelateResult<'tcx, T>
55 fn regions(&mut self, a: &'tcx ty::Region, b: &'tcx ty::Region)
56 -> RelateResult<'tcx, &'tcx ty::Region> {
57 debug!("{}.regions({:?}, {:?})",
64 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
65 debug!("{}.tys({:?}, {:?})", self.tag(),
67 if a == b { return Ok(a); }
69 match (&a.sty, &b.sty) {
70 (_, &ty::TyInfer(ty::FreshTy(_))) |
71 (_, &ty::TyInfer(ty::FreshIntTy(_))) |
72 (_, &ty::TyInfer(ty::FreshFloatTy(_))) => {
76 (&ty::TyInfer(_), _) |
77 (_, &ty::TyInfer(_)) => {
78 Err(TypeError::Sorts(relate::expected_found(self, &a, &b)))
81 (&ty::TyError, _) | (_, &ty::TyError) => {
82 Ok(self.tcx().types.err)
86 relate::super_relate_tys(self, a, b)
91 fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
92 -> RelateResult<'tcx, ty::Binder<T>>
95 Ok(ty::Binder(self.relate(a.skip_binder(), b.skip_binder())?))