]> git.proxmox.com Git - rustc.git/blob - src/librustc_typeck/check/demand.rs
Imported Upstream version 1.2.0+dfsg1
[rustc.git] / src / librustc_typeck / check / demand.rs
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.
4 //
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.
10
11
12 use check::{coercion, FnCtxt};
13 use middle::ty::{self, Ty};
14 use middle::infer;
15
16 use std::result::Result::{Err, Ok};
17 use syntax::ast;
18 use syntax::codemap::Span;
19
20 // Requires that the two types unify, and prints an error message if
21 // they don't.
22 pub fn suptype<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, sp: Span,
23 ty_expected: Ty<'tcx>, ty_actual: Ty<'tcx>) {
24 suptype_with_fn(fcx, sp, false, ty_expected, ty_actual,
25 |sp, e, a, s| { fcx.report_mismatched_types(sp, e, a, s) })
26 }
27
28 /// As `suptype`, but call `handle_err` if unification for subtyping fails.
29 pub fn suptype_with_fn<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>,
30 sp: Span,
31 b_is_expected: bool,
32 ty_a: Ty<'tcx>,
33 ty_b: Ty<'tcx>,
34 handle_err: F) where
35 F: FnOnce(Span, Ty<'tcx>, Ty<'tcx>, &ty::type_err<'tcx>),
36 {
37 // n.b.: order of actual, expected is reversed
38 match infer::mk_subty(fcx.infcx(), b_is_expected, infer::Misc(sp),
39 ty_b, ty_a) {
40 Ok(()) => { /* ok */ }
41 Err(ref err) => {
42 handle_err(sp, ty_a, ty_b, err);
43 }
44 }
45 }
46
47 pub fn eqtype<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, sp: Span,
48 expected: Ty<'tcx>, actual: Ty<'tcx>) {
49 match infer::mk_eqty(fcx.infcx(), false, infer::Misc(sp), actual, expected) {
50 Ok(()) => { /* ok */ }
51 Err(ref err) => { fcx.report_mismatched_types(sp, expected, actual, err); }
52 }
53 }
54
55 // Checks that the type of `expr` can be coerced to `expected`.
56 pub fn coerce<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
57 sp: Span,
58 expected: Ty<'tcx>,
59 expr: &ast::Expr) {
60 let expr_ty = fcx.expr_ty(expr);
61 debug!("demand::coerce(expected = {:?}, expr_ty = {:?})",
62 expected,
63 expr_ty);
64 let expr_ty = fcx.resolve_type_vars_if_possible(expr_ty);
65 let expected = fcx.resolve_type_vars_if_possible(expected);
66 match coercion::mk_assignty(fcx, expr, expr_ty, expected) {
67 Ok(()) => { /* ok */ }
68 Err(ref err) => {
69 fcx.report_mismatched_types(sp, expected, expr_ty, err);
70 }
71 }
72 }