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.
13 # Standalone Tests for the Inference Module
17 use driver::diagnostic;
18 use driver::diagnostic::Emitter;
20 use middle::lang_items;
21 use middle::region::{mod, CodeExtent};
23 use middle::resolve_lifetime;
24 use middle::stability;
26 use middle::subst::Subst;
27 use middle::ty::{mod, Ty};
28 use middle::typeck::infer::combine::Combine;
29 use middle::typeck::infer;
30 use middle::typeck::infer::lub::Lub;
31 use middle::typeck::infer::glb::Glb;
32 use session::{mod,config};
33 use syntax::{abi, ast, ast_map, ast_util};
35 use syntax::codemap::{Span, CodeMap, DUMMY_SP};
36 use syntax::diagnostic::{Level, RenderSpan, Bug, Fatal, Error, Warning, Note, Help};
37 use syntax::parse::token;
38 use util::ppaux::{ty_to_string, Repr, UserString};
40 use arena::TypedArena;
42 struct Env<'a, 'tcx: 'a> {
43 infcx: &'a infer::InferCtxt<'a, 'tcx>,
51 static EMPTY_SOURCE_STR: &'static str = "#![no_std]";
53 struct ExpectErrorEmitter {
57 fn remove_message(e: &mut ExpectErrorEmitter, msg: &str, lvl: Level) {
59 Bug | Fatal | Error => { }
60 Warning | Note | Help => { return; }
63 debug!("Error: {}", msg);
64 match e.messages.iter().position(|m| msg.contains(m.as_slice())) {
69 panic!("Unexpected error: {} Expected: {}",
75 impl Emitter for ExpectErrorEmitter {
77 _cmsp: Option<(&codemap::CodeMap, Span)>,
82 remove_message(self, msg, lvl);
85 fn custom_emit(&mut self,
86 _cm: &codemap::CodeMap,
91 remove_message(self, msg, lvl);
95 fn errors(msgs: &[&str]) -> (Box<Emitter+Send>, uint) {
96 let v = msgs.iter().map(|m| m.to_string()).collect();
97 (box ExpectErrorEmitter { messages: v } as Box<Emitter+Send>, msgs.len())
100 fn test_env(source_string: &str,
101 (emitter, expected_err_count): (Box<Emitter+Send>, uint),
104 config::basic_options();
105 options.debugging_opts |= config::VERBOSE;
108 let diagnostic_handler =
109 diagnostic::mk_handler(emitter);
110 let span_diagnostic_handler =
111 diagnostic::mk_span_handler(diagnostic_handler, codemap);
113 let sess = session::build_session_(options, None, span_diagnostic_handler);
114 let krate_config = Vec::new();
115 let input = driver::StrInput(source_string.to_string());
116 let krate = driver::phase_1_parse_input(&sess, krate_config, &input);
117 let krate = driver::phase_2_configure_and_expand(&sess, krate, "test", None)
118 .expect("phase 2 aborted");
120 let mut forest = ast_map::Forest::new(krate);
121 let ast_map = driver::assign_node_ids_and_map(&sess, &mut forest);
122 let krate = ast_map.krate();
124 // run just enough stuff to build a tcx:
125 let lang_items = lang_items::collect_language_items(krate, &sess);
126 let resolve::CrateMap { def_map, freevars, capture_mode_map, .. } =
127 resolve::resolve_crate(&sess, &lang_items, krate);
128 let named_region_map = resolve_lifetime::krate(&sess, krate, &def_map);
129 let region_map = region::resolve_crate(&sess, krate);
130 let stability_index = stability::Index::build(krate);
131 let type_arena = TypedArena::new();
132 let tcx = ty::mk_ctxt(sess,
142 let infcx = infer::new_infer_ctxt(&tcx);
143 body(Env { infcx: &infcx });
144 infcx.resolve_regions_and_report_errors();
145 assert_eq!(tcx.sess.err_count(), expected_err_count);
148 impl<'a, 'tcx> Env<'a, 'tcx> {
149 pub fn create_region_hierarchy(&self, rh: &RH) {
150 for child_rh in rh.sub.iter() {
151 self.create_region_hierarchy(child_rh);
152 self.infcx.tcx.region_maps.record_encl_scope(
153 CodeExtent::from_node_id(child_rh.id),
154 CodeExtent::from_node_id(rh.id));
158 pub fn create_simple_region_hierarchy(&self) {
159 // creates a region hierarchy where 1 is root, 10 and 11 are
160 // children of 1, etc
161 self.create_region_hierarchy(
169 #[allow(dead_code)] // this seems like it could be useful, even if we don't use it now
170 pub fn lookup_item(&self, names: &[String]) -> ast::NodeId {
171 return match search_mod(self, &self.infcx.tcx.map.krate().module, 0, names) {
174 panic!("no item found: `{}`", names.connect("::"));
178 fn search_mod(this: &Env,
182 -> Option<ast::NodeId> {
183 assert!(idx < names.len());
184 for item in m.items.iter() {
185 if item.ident.user_string(this.infcx.tcx) == names[idx] {
186 return search(this, &**item, idx+1, names);
192 fn search(this: &Env,
196 -> Option<ast::NodeId> {
197 if idx == names.len() {
201 return match it.node {
202 ast::ItemConst(..) | ast::ItemStatic(..) | ast::ItemFn(..) |
203 ast::ItemForeignMod(..) | ast::ItemTy(..) => {
207 ast::ItemEnum(..) | ast::ItemStruct(..) |
208 ast::ItemTrait(..) | ast::ItemImpl(..) |
209 ast::ItemMac(..) => {
213 ast::ItemMod(ref m) => {
214 search_mod(this, m, idx, names)
220 pub fn make_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
221 match infer::mk_subty(self.infcx, true, infer::Misc(DUMMY_SP), a, b) {
223 Err(ref e) => panic!("Encountered error: {}",
224 ty::type_err_to_str(self.infcx.tcx, e))
228 pub fn is_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
229 match infer::can_mk_subty(self.infcx, a, b) {
235 pub fn assert_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) {
236 if !self.is_subtype(a, b) {
237 panic!("{} is not a subtype of {}, but it should be",
238 self.ty_to_string(a),
239 self.ty_to_string(b));
243 pub fn assert_eq(&self, a: Ty<'tcx>, b: Ty<'tcx>) {
244 self.assert_subtype(a, b);
245 self.assert_subtype(b, a);
248 pub fn ty_to_string(&self, a: Ty<'tcx>) -> String {
249 ty_to_string(self.infcx.tcx, a)
253 input_tys: &[Ty<'tcx>],
257 ty::mk_ctor_fn(self.infcx.tcx, input_tys, output_ty)
260 pub fn t_nil(&self) -> Ty<'tcx> {
261 ty::mk_nil(self.infcx.tcx)
264 pub fn t_pair(&self, ty1: Ty<'tcx>, ty2: Ty<'tcx>) -> Ty<'tcx> {
265 ty::mk_tup(self.infcx.tcx, vec![ty1, ty2])
268 pub fn t_closure(&self,
269 input_tys: &[Ty<'tcx>],
271 region_bound: ty::Region)
274 ty::mk_closure(self.infcx.tcx, ty::ClosureTy {
275 fn_style: ast::NormalFn,
277 store: ty::RegionTraitStore(region_bound, ast::MutMutable),
278 bounds: ty::region_existential_bound(region_bound),
280 inputs: input_tys.to_vec(),
281 output: ty::FnConverging(output_ty),
288 pub fn t_param(&self, space: subst::ParamSpace, index: uint) -> Ty<'tcx> {
289 ty::mk_param(self.infcx.tcx, space, index, ast_util::local_def(ast::DUMMY_NODE_ID))
292 pub fn re_early_bound(&self,
293 space: subst::ParamSpace,
298 let name = token::intern(name);
299 ty::ReEarlyBound(ast::DUMMY_NODE_ID, space, index, name)
302 pub fn re_late_bound_with_debruijn(&self, id: uint, debruijn: ty::DebruijnIndex) -> ty::Region {
303 ty::ReLateBound(debruijn, ty::BrAnon(id))
306 pub fn t_rptr(&self, r: ty::Region) -> Ty<'tcx> {
307 ty::mk_imm_rptr(self.infcx.tcx, r, ty::mk_int())
310 pub fn t_rptr_late_bound(&self, id: uint) -> Ty<'tcx> {
311 ty::mk_imm_rptr(self.infcx.tcx,
312 self.re_late_bound_with_debruijn(id, ty::DebruijnIndex::new(1)),
316 pub fn t_rptr_late_bound_with_debruijn(&self,
318 debruijn: ty::DebruijnIndex)
320 ty::mk_imm_rptr(self.infcx.tcx,
321 self.re_late_bound_with_debruijn(id, debruijn),
325 pub fn t_rptr_scope(&self, id: ast::NodeId) -> Ty<'tcx> {
326 ty::mk_imm_rptr(self.infcx.tcx, ty::ReScope(CodeExtent::from_node_id(id)), ty::mk_int())
329 pub fn re_free(&self, nid: ast::NodeId, id: uint) -> ty::Region {
330 ty::ReFree(ty::FreeRegion { scope: CodeExtent::from_node_id(nid),
331 bound_region: ty::BrAnon(id)})
334 pub fn t_rptr_free(&self, nid: ast::NodeId, id: uint) -> Ty<'tcx> {
335 ty::mk_imm_rptr(self.infcx.tcx, self.re_free(nid, id), ty::mk_int())
338 pub fn t_rptr_static(&self) -> Ty<'tcx> {
339 ty::mk_imm_rptr(self.infcx.tcx, ty::ReStatic, ty::mk_int())
342 pub fn dummy_type_trace(&self) -> infer::TypeTrace<'tcx> {
343 infer::TypeTrace::dummy()
346 pub fn lub(&self) -> Lub<'a, 'tcx> {
347 let trace = self.dummy_type_trace();
348 Lub(self.infcx.combine_fields(true, trace))
351 pub fn glb(&self) -> Glb<'a, 'tcx> {
352 let trace = self.dummy_type_trace();
353 Glb(self.infcx.combine_fields(true, trace))
356 pub fn make_lub_ty(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> Ty<'tcx> {
357 match self.lub().tys(t1, t2) {
359 Err(ref e) => panic!("unexpected error computing LUB: {}",
360 ty::type_err_to_str(self.infcx.tcx, e))
364 /// Checks that `LUB(t1,t2) == t_lub`
365 pub fn check_lub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>, t_lub: Ty<'tcx>) {
366 match self.lub().tys(t1, t2) {
368 self.assert_eq(t, t_lub);
371 panic!("unexpected error in LUB: {}",
372 ty::type_err_to_str(self.infcx.tcx, e))
377 /// Checks that `GLB(t1,t2) == t_glb`
378 pub fn check_glb(&self, t1: Ty<'tcx>, t2: Ty<'tcx>, t_glb: Ty<'tcx>) {
379 debug!("check_glb(t1={}, t2={}, t_glb={})",
380 self.ty_to_string(t1),
381 self.ty_to_string(t2),
382 self.ty_to_string(t_glb));
383 match self.glb().tys(t1, t2) {
385 panic!("unexpected error computing LUB: {}", e)
388 self.assert_eq(t, t_glb);
390 // sanity check for good measure:
391 self.assert_subtype(t, t1);
392 self.assert_subtype(t, t2);
399 fn contravariant_region_ptr_ok() {
400 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
401 env.create_simple_region_hierarchy();
402 let t_rptr1 = env.t_rptr_scope(1);
403 let t_rptr10 = env.t_rptr_scope(10);
404 env.assert_eq(t_rptr1, t_rptr1);
405 env.assert_eq(t_rptr10, t_rptr10);
406 env.make_subtype(t_rptr1, t_rptr10);
411 fn contravariant_region_ptr_err() {
412 test_env(EMPTY_SOURCE_STR,
413 errors(&["lifetime mismatch"]),
415 env.create_simple_region_hierarchy();
416 let t_rptr1 = env.t_rptr_scope(1);
417 let t_rptr10 = env.t_rptr_scope(10);
418 env.assert_eq(t_rptr1, t_rptr1);
419 env.assert_eq(t_rptr10, t_rptr10);
421 // will cause an error when regions are resolved
422 env.make_subtype(t_rptr10, t_rptr1);
427 fn lub_bound_bound() {
428 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
429 let t_rptr_bound1 = env.t_rptr_late_bound(1);
430 let t_rptr_bound2 = env.t_rptr_late_bound(2);
431 env.check_lub(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
432 env.t_fn(&[t_rptr_bound2], ty::mk_int()),
433 env.t_fn(&[t_rptr_bound1], ty::mk_int()));
438 fn lub_bound_free() {
439 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
440 let t_rptr_bound1 = env.t_rptr_late_bound(1);
441 let t_rptr_free1 = env.t_rptr_free(0, 1);
442 env.check_lub(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
443 env.t_fn(&[t_rptr_free1], ty::mk_int()),
444 env.t_fn(&[t_rptr_free1], ty::mk_int()));
449 fn lub_bound_static() {
450 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
451 let t_rptr_bound1 = env.t_rptr_late_bound(1);
452 let t_rptr_static = env.t_rptr_static();
453 env.check_lub(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
454 env.t_fn(&[t_rptr_static], ty::mk_int()),
455 env.t_fn(&[t_rptr_static], ty::mk_int()));
460 fn lub_bound_bound_inverse_order() {
461 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
462 let t_rptr_bound1 = env.t_rptr_late_bound(1);
463 let t_rptr_bound2 = env.t_rptr_late_bound(2);
464 env.check_lub(env.t_fn(&[t_rptr_bound1, t_rptr_bound2], t_rptr_bound1),
465 env.t_fn(&[t_rptr_bound2, t_rptr_bound1], t_rptr_bound1),
466 env.t_fn(&[t_rptr_bound1, t_rptr_bound1], t_rptr_bound1));
472 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
473 let t_rptr_free1 = env.t_rptr_free(0, 1);
474 let t_rptr_free2 = env.t_rptr_free(0, 2);
475 let t_rptr_static = env.t_rptr_static();
476 env.check_lub(env.t_fn(&[t_rptr_free1], ty::mk_int()),
477 env.t_fn(&[t_rptr_free2], ty::mk_int()),
478 env.t_fn(&[t_rptr_static], ty::mk_int()));
483 fn lub_returning_scope() {
484 test_env(EMPTY_SOURCE_STR,
485 errors(&["cannot infer an appropriate lifetime"]), |env| {
486 let t_rptr_scope10 = env.t_rptr_scope(10);
487 let t_rptr_scope11 = env.t_rptr_scope(11);
489 // this should generate an error when regions are resolved
490 env.make_lub_ty(env.t_fn(&[], t_rptr_scope10),
491 env.t_fn(&[], t_rptr_scope11));
496 fn glb_free_free_with_common_scope() {
497 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
498 let t_rptr_free1 = env.t_rptr_free(0, 1);
499 let t_rptr_free2 = env.t_rptr_free(0, 2);
500 let t_rptr_scope = env.t_rptr_scope(0);
501 env.check_glb(env.t_fn(&[t_rptr_free1], ty::mk_int()),
502 env.t_fn(&[t_rptr_free2], ty::mk_int()),
503 env.t_fn(&[t_rptr_scope], ty::mk_int()));
508 fn glb_bound_bound() {
509 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
510 let t_rptr_bound1 = env.t_rptr_late_bound(1);
511 let t_rptr_bound2 = env.t_rptr_late_bound(2);
512 env.check_glb(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
513 env.t_fn(&[t_rptr_bound2], ty::mk_int()),
514 env.t_fn(&[t_rptr_bound1], ty::mk_int()));
519 fn glb_bound_free() {
520 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
521 let t_rptr_bound1 = env.t_rptr_late_bound(1);
522 let t_rptr_free1 = env.t_rptr_free(0, 1);
523 env.check_glb(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
524 env.t_fn(&[t_rptr_free1], ty::mk_int()),
525 env.t_fn(&[t_rptr_bound1], ty::mk_int()));
530 fn glb_bound_static() {
531 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
532 let t_rptr_bound1 = env.t_rptr_late_bound(1);
533 let t_rptr_static = env.t_rptr_static();
534 env.check_glb(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
535 env.t_fn(&[t_rptr_static], ty::mk_int()),
536 env.t_fn(&[t_rptr_bound1], ty::mk_int()));
541 fn subst_ty_renumber_bound() {
543 * Test substituting a bound region into a function, which introduces another
544 * level of binding. This requires adjusting the Debruijn index.
547 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
549 // Theta = [A -> &'a foo]
551 let t_rptr_bound1 = env.t_rptr_late_bound(1);
555 let t_param = env.t_param(subst::TypeSpace, 0);
556 env.t_fn(&[t_param], env.t_nil())
559 let substs = subst::Substs::new_type(vec![t_rptr_bound1], vec![]);
560 let t_substituted = t_source.subst(env.infcx.tcx, &substs);
562 // t_expected = fn(&'a int)
564 let t_ptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
565 env.t_fn(&[t_ptr_bound2], env.t_nil())
568 debug!("subst_bound: t_source={} substs={} t_substituted={} t_expected={}",
569 t_source.repr(env.infcx.tcx),
570 substs.repr(env.infcx.tcx),
571 t_substituted.repr(env.infcx.tcx),
572 t_expected.repr(env.infcx.tcx));
574 assert_eq!(t_substituted, t_expected);
579 fn subst_ty_renumber_some_bounds() {
581 * Test substituting a bound region into a function, which introduces another
582 * level of binding. This requires adjusting the Debruijn index.
585 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
587 // Theta = [A -> &'a foo]
589 let t_rptr_bound1 = env.t_rptr_late_bound(1);
591 // t_source = (A, fn(A))
593 let t_param = env.t_param(subst::TypeSpace, 0);
594 env.t_pair(t_param, env.t_fn(&[t_param], env.t_nil()))
597 let substs = subst::Substs::new_type(vec![t_rptr_bound1], vec![]);
598 let t_substituted = t_source.subst(env.infcx.tcx, &substs);
600 // t_expected = (&'a int, fn(&'a int))
602 // but not that the Debruijn index is different in the different cases.
604 let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
605 env.t_pair(t_rptr_bound1, env.t_fn(&[t_rptr_bound2], env.t_nil()))
608 debug!("subst_bound: t_source={} substs={} t_substituted={} t_expected={}",
609 t_source.repr(env.infcx.tcx),
610 substs.repr(env.infcx.tcx),
611 t_substituted.repr(env.infcx.tcx),
612 t_expected.repr(env.infcx.tcx));
614 assert_eq!(t_substituted, t_expected);
621 * Test that we correctly compute whether a type has escaping
625 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
627 // Theta = [A -> &'a foo]
629 assert!(!ty::type_has_escaping_regions(env.t_nil()));
631 let t_rptr_free1 = env.t_rptr_free(0, 1);
632 assert!(!ty::type_has_escaping_regions(t_rptr_free1));
634 let t_rptr_bound1 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(1));
635 assert!(ty::type_has_escaping_regions(t_rptr_bound1));
637 let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
638 assert!(ty::type_has_escaping_regions(t_rptr_bound2));
641 let t_param = env.t_param(subst::TypeSpace, 0);
642 assert!(!ty::type_has_escaping_regions(t_param));
643 let t_fn = env.t_fn(&[t_param], env.t_nil());
644 assert!(!ty::type_has_escaping_regions(t_fn));
647 let t_fn = env.t_closure(&[t_rptr_bound1], env.t_nil(), env.re_free(0, 1));
648 assert!(!ty::type_has_escaping_regions(t_fn));
650 // t_fn = |&int|+'a (where &int has depth 2)
651 let t_fn = env.t_closure(&[t_rptr_bound2], env.t_nil(), env.re_free(0, 1));
652 assert!(ty::type_has_escaping_regions(t_fn));
654 // t_fn = |&int|+&int
655 let t_fn = env.t_closure(&[t_rptr_bound1], env.t_nil(),
656 env.re_late_bound_with_debruijn(1, ty::DebruijnIndex::new(1)));
657 assert!(ty::type_has_escaping_regions(t_fn));
662 fn subst_region_renumber_region() {
664 * Test applying a substitution where the value being substituted
665 * for an early-bound region is a late-bound region.
668 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
669 let re_bound1 = env.re_late_bound_with_debruijn(1, ty::DebruijnIndex::new(1));
671 // type t_source<'a> = fn(&'a int)
673 let re_early = env.re_early_bound(subst::TypeSpace, 0, "'a");
674 env.t_fn(&[env.t_rptr(re_early)], env.t_nil())
677 let substs = subst::Substs::new_type(vec![], vec![re_bound1]);
678 let t_substituted = t_source.subst(env.infcx.tcx, &substs);
680 // t_expected = fn(&'a int)
682 // but not that the Debruijn index is different in the different cases.
684 let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
685 env.t_fn(&[t_rptr_bound2], env.t_nil())
688 debug!("subst_bound: t_source={} substs={} t_substituted={} t_expected={}",
689 t_source.repr(env.infcx.tcx),
690 substs.repr(env.infcx.tcx),
691 t_substituted.repr(env.infcx.tcx),
692 t_expected.repr(env.infcx.tcx));
694 assert_eq!(t_substituted, t_expected);