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 //! # Standalone Tests for the Inference Module
13 use std::path::PathBuf;
18 use rustc_resolve::MakeGlobMap;
19 use rustc::middle::region;
20 use rustc::ty::subst::Subst;
21 use rustc::traits::ObligationCause;
22 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
23 use rustc::ty::maps::OnDiskCache;
24 use rustc::infer::{self, InferOk, InferResult};
25 use rustc::infer::outlives::env::OutlivesEnvironment;
26 use rustc::infer::type_variable::TypeVariableOrigin;
27 use rustc_metadata::cstore::CStore;
28 use rustc::hir::map as hir_map;
29 use rustc::session::{self, config};
30 use rustc::session::config::{OutputFilenames, OutputTypes};
31 use rustc_data_structures::sync::{self, Lrc};
34 use rustc_target::spec::abi::Abi;
35 use syntax::codemap::{CodeMap, FilePathMapping, FileName};
37 use errors::emitter::Emitter;
38 use errors::{Level, DiagnosticBuilder};
39 use syntax::feature_gate::UnstableFeatures;
40 use syntax::symbol::Symbol;
41 use syntax_pos::DUMMY_SP;
45 struct Env<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
46 infcx: &'a infer::InferCtxt<'a, 'gcx, 'tcx>,
47 region_scope_tree: &'a mut region::ScopeTree,
48 param_env: ty::ParamEnv<'tcx>,
56 const EMPTY_SOURCE_STR: &'static str = "#![feature(no_core)] #![no_core]";
58 struct ExpectErrorEmitter {
59 messages: Vec<String>,
62 fn remove_message(e: &mut ExpectErrorEmitter, msg: &str, lvl: Level) {
64 Level::Bug | Level::Fatal | Level::Error => {}
70 debug!("Error: {}", msg);
71 match e.messages.iter().position(|m| msg.contains(m)) {
76 debug!("Unexpected error: {} Expected: {:?}", msg, e.messages);
77 panic!("Unexpected error: {} Expected: {:?}", msg, e.messages);
82 impl Emitter for ExpectErrorEmitter {
83 fn emit(&mut self, db: &DiagnosticBuilder) {
84 remove_message(self, &db.message(), db.level);
85 for child in &db.children {
86 remove_message(self, &child.message(), child.level);
91 fn errors(msgs: &[&str]) -> (Box<Emitter + sync::Send>, usize) {
92 let v = msgs.iter().map(|m| m.to_string()).collect();
93 (box ExpectErrorEmitter { messages: v } as Box<Emitter + sync::Send>, msgs.len())
96 fn test_env<F>(source_string: &str,
97 args: (Box<Emitter + sync::Send>, usize),
101 syntax::with_globals(|| {
102 let mut options = config::basic_options();
103 options.debugging_opts.verbose = true;
104 options.unstable_features = UnstableFeatures::Allow;
106 driver::spawn_thread_pool(options, |options| {
107 test_env_with_pool(options, source_string, args, body)
112 fn test_env_with_pool<F>(
113 options: config::Options,
115 (emitter, expected_err_count): (Box<Emitter + sync::Send>, usize),
120 let diagnostic_handler = errors::Handler::with_emitter(true, false, emitter);
121 let sess = session::build_session_(options,
124 Lrc::new(CodeMap::new(FilePathMapping::empty())));
125 let cstore = CStore::new(::get_trans(&sess).metadata_loader());
126 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
127 let input = config::Input::Str {
128 name: FileName::Anon,
129 input: source_string.to_string(),
131 let krate = driver::phase_1_parse_input(&driver::CompileController::basic(),
134 let driver::ExpansionResult { defs, resolutions, mut hir_forest, .. } = {
135 driver::phase_2_configure_and_expand(&sess,
143 .expect("phase 2 aborted")
146 let arenas = ty::AllArenas::new();
147 let hir_map = hir_map::map_crate(&sess, &cstore, &mut hir_forest, &defs);
149 // run just enough stuff to build a tcx:
150 let (tx, _rx) = mpsc::channel();
151 let outputs = OutputFilenames {
152 out_directory: PathBuf::new(),
153 out_filestem: String::new(),
154 single_output_file: None,
155 extra: String::new(),
156 outputs: OutputTypes::new(&[]),
158 TyCtxt::create_and_enter(&sess,
160 ty::maps::Providers::default(),
161 ty::maps::Providers::default(),
165 OnDiskCache::new_empty(sess.codemap()),
170 tcx.infer_ctxt().enter(|infcx| {
171 let mut region_scope_tree = region::ScopeTree::default();
172 let param_env = ty::ParamEnv::empty();
175 region_scope_tree: &mut region_scope_tree,
176 param_env: param_env,
178 let outlives_env = OutlivesEnvironment::new(param_env);
179 let def_id = tcx.hir.local_def_id(ast::CRATE_NODE_ID);
180 infcx.resolve_regions_and_report_errors(def_id, ®ion_scope_tree, &outlives_env);
181 assert_eq!(tcx.sess.err_count(), expected_err_count);
186 impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> {
187 pub fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
191 pub fn create_region_hierarchy(&mut self, rh: &RH, parent: region::Scope) {
192 let me = region::Scope::Node(rh.id);
193 self.region_scope_tree.record_scope_parent(me, Some(parent));
194 for child_rh in rh.sub {
195 self.create_region_hierarchy(child_rh, me);
199 pub fn create_simple_region_hierarchy(&mut self) {
200 // creates a region hierarchy where 1 is root, 10 and 11 are
201 // children of 1, etc
203 let dscope = region::Scope::Destruction(hir::ItemLocalId(1));
204 self.region_scope_tree.record_scope_parent(dscope, None);
205 self.create_region_hierarchy(&RH {
206 id: hir::ItemLocalId(1),
208 id: hir::ItemLocalId(10),
212 id: hir::ItemLocalId(11),
218 #[allow(dead_code)] // this seems like it could be useful, even if we don't use it now
219 pub fn lookup_item(&self, names: &[String]) -> ast::NodeId {
220 return match search_mod(self, &self.infcx.tcx.hir.krate().module, 0, names) {
223 panic!("no item found: `{}`", names.join("::"));
227 fn search_mod(this: &Env,
231 -> Option<ast::NodeId> {
232 assert!(idx < names.len());
233 for item in &m.item_ids {
234 let item = this.infcx.tcx.hir.expect_item(item.id);
235 if item.name.to_string() == names[idx] {
236 return search(this, item, idx + 1, names);
242 fn search(this: &Env, it: &hir::Item, idx: usize, names: &[String]) -> Option<ast::NodeId> {
243 if idx == names.len() {
247 return match it.node {
249 hir::ItemExternCrate(..) |
251 hir::ItemStatic(..) |
253 hir::ItemForeignMod(..) |
254 hir::ItemGlobalAsm(..) |
255 hir::ItemTy(..) => None,
258 hir::ItemStruct(..) |
261 hir::ItemTraitAlias(..) |
262 hir::ItemImpl(..) => None,
264 hir::ItemMod(ref m) => search_mod(this, m, idx, names),
269 pub fn make_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
270 match self.infcx.at(&ObligationCause::dummy(), self.param_env).sub(a, b) {
272 Err(ref e) => panic!("Encountered error: {}", e),
276 pub fn is_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
277 self.infcx.can_sub(self.param_env, a, b).is_ok()
280 pub fn assert_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) {
281 if !self.is_subtype(a, b) {
282 panic!("{} is not a subtype of {}, but it should be", a, b);
286 pub fn assert_eq(&self, a: Ty<'tcx>, b: Ty<'tcx>) {
287 self.assert_subtype(a, b);
288 self.assert_subtype(b, a);
291 pub fn t_fn(&self, input_tys: &[Ty<'tcx>], output_ty: Ty<'tcx>) -> Ty<'tcx> {
292 self.infcx.tcx.mk_fn_ptr(ty::Binder::bind(self.infcx.tcx.mk_fn_sig(
293 input_tys.iter().cloned(),
296 hir::Unsafety::Normal,
301 pub fn t_nil(&self) -> Ty<'tcx> {
302 self.infcx.tcx.mk_nil()
305 pub fn t_pair(&self, ty1: Ty<'tcx>, ty2: Ty<'tcx>) -> Ty<'tcx> {
306 self.infcx.tcx.intern_tup(&[ty1, ty2])
309 pub fn t_param(&self, index: u32) -> Ty<'tcx> {
310 let name = format!("T{}", index);
311 self.infcx.tcx.mk_param(index, Symbol::intern(&name).as_interned_str())
314 pub fn re_early_bound(&self, index: u32, name: &'static str) -> ty::Region<'tcx> {
315 let name = Symbol::intern(name).as_interned_str();
316 self.infcx.tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
317 def_id: self.infcx.tcx.hir.local_def_id(ast::CRATE_NODE_ID),
323 pub fn re_late_bound_with_debruijn(&self,
325 debruijn: ty::DebruijnIndex)
326 -> ty::Region<'tcx> {
327 self.infcx.tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(id)))
330 pub fn t_rptr(&self, r: ty::Region<'tcx>) -> Ty<'tcx> {
331 self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize)
334 pub fn t_rptr_late_bound(&self, id: u32) -> Ty<'tcx> {
335 let r = self.re_late_bound_with_debruijn(id, ty::DebruijnIndex::new(1));
336 self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize)
339 pub fn t_rptr_late_bound_with_debruijn(&self,
341 debruijn: ty::DebruijnIndex)
343 let r = self.re_late_bound_with_debruijn(id, debruijn);
344 self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize)
347 pub fn t_rptr_scope(&self, id: u32) -> Ty<'tcx> {
348 let r = ty::ReScope(region::Scope::Node(hir::ItemLocalId(id)));
349 self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), self.tcx().types.isize)
352 pub fn re_free(&self, id: u32) -> ty::Region<'tcx> {
353 self.infcx.tcx.mk_region(ty::ReFree(ty::FreeRegion {
354 scope: self.infcx.tcx.hir.local_def_id(ast::CRATE_NODE_ID),
355 bound_region: ty::BrAnon(id),
359 pub fn t_rptr_free(&self, id: u32) -> Ty<'tcx> {
360 let r = self.re_free(id);
361 self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize)
364 pub fn sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> InferResult<'tcx, ()> {
365 self.infcx.at(&ObligationCause::dummy(), self.param_env).sub(t1, t2)
368 /// Checks that `t1 <: t2` is true (this may register additional
370 pub fn check_sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) {
371 match self.sub(t1, t2) {
372 Ok(InferOk { obligations, value: () }) => {
373 // None of these tests should require nested obligations:
374 assert!(obligations.is_empty());
377 panic!("unexpected error computing sub({:?},{:?}): {}", t1, t2, e);
382 /// Checks that `t1 <: t2` is false (this may register additional
384 pub fn check_not_sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) {
385 match self.sub(t1, t2) {
388 panic!("unexpected success computing sub({:?},{:?})", t1, t2);
395 fn contravariant_region_ptr_ok() {
396 test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
397 env.create_simple_region_hierarchy();
398 let t_rptr1 = env.t_rptr_scope(1);
399 let t_rptr10 = env.t_rptr_scope(10);
400 env.assert_eq(t_rptr1, t_rptr1);
401 env.assert_eq(t_rptr10, t_rptr10);
402 env.make_subtype(t_rptr1, t_rptr10);
407 fn contravariant_region_ptr_err() {
408 test_env(EMPTY_SOURCE_STR, errors(&["mismatched types"]), |mut env| {
409 env.create_simple_region_hierarchy();
410 let t_rptr1 = env.t_rptr_scope(1);
411 let t_rptr10 = env.t_rptr_scope(10);
412 env.assert_eq(t_rptr1, t_rptr1);
413 env.assert_eq(t_rptr10, t_rptr10);
415 // will cause an error when regions are resolved
416 env.make_subtype(t_rptr10, t_rptr1);
421 fn sub_free_bound_false() {
424 //! fn(&'a isize) <: for<'b> fn(&'b isize)
428 test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
429 env.create_simple_region_hierarchy();
430 let t_rptr_free1 = env.t_rptr_free(1);
431 let t_rptr_bound1 = env.t_rptr_late_bound(1);
432 env.check_not_sub(env.t_fn(&[t_rptr_free1], env.tcx().types.isize),
433 env.t_fn(&[t_rptr_bound1], env.tcx().types.isize));
438 fn sub_bound_free_true() {
441 //! for<'a> fn(&'a isize) <: fn(&'b isize)
445 test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
446 env.create_simple_region_hierarchy();
447 let t_rptr_bound1 = env.t_rptr_late_bound(1);
448 let t_rptr_free1 = env.t_rptr_free(1);
449 env.check_sub(env.t_fn(&[t_rptr_bound1], env.tcx().types.isize),
450 env.t_fn(&[t_rptr_free1], env.tcx().types.isize));
455 fn sub_free_bound_false_infer() {
458 //! fn(_#1) <: for<'b> fn(&'b isize)
460 //! does NOT hold for any instantiation of `_#1`.
462 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
463 let t_infer1 = env.infcx.next_ty_var(TypeVariableOrigin::MiscVariable(DUMMY_SP));
464 let t_rptr_bound1 = env.t_rptr_late_bound(1);
465 env.check_not_sub(env.t_fn(&[t_infer1], env.tcx().types.isize),
466 env.t_fn(&[t_rptr_bound1], env.tcx().types.isize));
470 /// Test substituting a bound region into a function, which introduces another level of binding.
471 /// This requires adjusting the Debruijn index.
473 fn subst_ty_renumber_bound() {
475 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
477 // Theta = [A -> &'a foo]
479 let t_rptr_bound1 = env.t_rptr_late_bound(1);
483 let t_param = env.t_param(0);
484 env.t_fn(&[t_param], env.t_nil())
487 let substs = env.infcx.tcx.intern_substs(&[t_rptr_bound1.into()]);
488 let t_substituted = t_source.subst(env.infcx.tcx, substs);
490 // t_expected = fn(&'a isize)
492 let t_ptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
493 env.t_fn(&[t_ptr_bound2], env.t_nil())
496 debug!("subst_bound: t_source={:?} substs={:?} t_substituted={:?} t_expected={:?}",
502 assert_eq!(t_substituted, t_expected);
506 /// Test substituting a bound region into a function, which introduces another level of binding.
507 /// This requires adjusting the Debruijn index.
509 fn subst_ty_renumber_some_bounds() {
510 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
512 // Theta = [A -> &'a foo]
514 let t_rptr_bound1 = env.t_rptr_late_bound(1);
516 // t_source = (A, fn(A))
518 let t_param = env.t_param(0);
519 env.t_pair(t_param, env.t_fn(&[t_param], env.t_nil()))
522 let substs = env.infcx.tcx.intern_substs(&[t_rptr_bound1.into()]);
523 let t_substituted = t_source.subst(env.infcx.tcx, substs);
525 // t_expected = (&'a isize, fn(&'a isize))
527 // but not that the Debruijn index is different in the different cases.
529 let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
530 env.t_pair(t_rptr_bound1, env.t_fn(&[t_rptr_bound2], env.t_nil()))
533 debug!("subst_bound: t_source={:?} substs={:?} t_substituted={:?} t_expected={:?}",
539 assert_eq!(t_substituted, t_expected);
543 /// Test that we correctly compute whether a type has escaping regions or not.
547 test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
549 // Theta = [A -> &'a foo]
550 env.create_simple_region_hierarchy();
552 assert!(!env.t_nil().has_escaping_regions());
554 let t_rptr_free1 = env.t_rptr_free(1);
555 assert!(!t_rptr_free1.has_escaping_regions());
557 let t_rptr_bound1 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(1));
558 assert!(t_rptr_bound1.has_escaping_regions());
560 let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
561 assert!(t_rptr_bound2.has_escaping_regions());
564 let t_param = env.t_param(0);
565 assert!(!t_param.has_escaping_regions());
566 let t_fn = env.t_fn(&[t_param], env.t_nil());
567 assert!(!t_fn.has_escaping_regions());
571 /// Test applying a substitution where the value being substituted for an early-bound region is a
572 /// late-bound region.
574 fn subst_region_renumber_region() {
575 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
576 let re_bound1 = env.re_late_bound_with_debruijn(1, ty::DebruijnIndex::new(1));
578 // type t_source<'a> = fn(&'a isize)
580 let re_early = env.re_early_bound(0, "'a");
581 env.t_fn(&[env.t_rptr(re_early)], env.t_nil())
584 let substs = env.infcx.tcx.intern_substs(&[re_bound1.into()]);
585 let t_substituted = t_source.subst(env.infcx.tcx, substs);
587 // t_expected = fn(&'a isize)
589 // but not that the Debruijn index is different in the different cases.
591 let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
592 env.t_fn(&[t_rptr_bound2], env.t_nil())
595 debug!("subst_bound: t_source={:?} substs={:?} t_substituted={:?} t_expected={:?}",
601 assert_eq!(t_substituted, t_expected);
607 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
608 let tcx = env.infcx.tcx;
609 let int_ty = tcx.types.isize;
610 let usize_ty = tcx.types.usize;
611 let tup1_ty = tcx.intern_tup(&[int_ty, usize_ty, int_ty, usize_ty]);
612 let tup2_ty = tcx.intern_tup(&[tup1_ty, tup1_ty, usize_ty]);
613 let walked: Vec<_> = tup2_ty.walk().collect();
615 [tup2_ty, tup1_ty, int_ty, usize_ty, int_ty, usize_ty, tup1_ty, int_ty,
616 usize_ty, int_ty, usize_ty, usize_ty]);
621 fn walk_ty_skip_subtree() {
622 test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
623 let tcx = env.infcx.tcx;
624 let int_ty = tcx.types.isize;
625 let usize_ty = tcx.types.usize;
626 let tup1_ty = tcx.intern_tup(&[int_ty, usize_ty, int_ty, usize_ty]);
627 let tup2_ty = tcx.intern_tup(&[tup1_ty, tup1_ty, usize_ty]);
629 // types we expect to see (in order), plus a boolean saying
630 // whether to skip the subtree.
631 let mut expected = vec![(tup2_ty, false),
637 (tup1_ty, true), // skip the isize/usize/isize/usize
641 let mut walker = tup2_ty.walk();
642 while let Some(t) = walker.next() {
643 debug!("walked to {:?}", t);
644 let (expected_ty, skip) = expected.pop().unwrap();
645 assert_eq!(t, expected_ty);
647 walker.skip_current_subtree();
651 assert!(expected.is_empty());