]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/test.rs
rustdoc: pretty-print Unevaluated expressions in types.
[rust.git] / src / librustc_driver / test.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 //! # Standalone Tests for the Inference Module
12
13 use driver;
14 use rustc::dep_graph::DepGraph;
15 use rustc_lint;
16 use rustc_resolve::MakeGlobMap;
17 use rustc_trans;
18 use rustc::middle::free_region::FreeRegionMap;
19 use rustc::middle::region;
20 use rustc::middle::resolve_lifetime;
21 use rustc::ty::subst::{Kind, Subst};
22 use rustc::traits::{ObligationCause, Reveal};
23 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
24 use rustc::infer::{self, InferOk, InferResult};
25 use rustc::infer::type_variable::TypeVariableOrigin;
26 use rustc_metadata::cstore::CStore;
27 use rustc::hir::map as hir_map;
28 use rustc::mir::transform::Passes;
29 use rustc::session::{self, config};
30 use std::rc::Rc;
31 use syntax::ast;
32 use syntax::abi::Abi;
33 use syntax::codemap::{CodeMap, FilePathMapping};
34 use errors;
35 use errors::emitter::Emitter;
36 use errors::{Level, DiagnosticBuilder};
37 use syntax::feature_gate::UnstableFeatures;
38 use syntax::symbol::Symbol;
39 use syntax_pos::DUMMY_SP;
40 use arena::DroplessArena;
41
42 use rustc::hir;
43
44 struct Env<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
45     infcx: &'a infer::InferCtxt<'a, 'gcx, 'tcx>,
46     region_scope_tree: &'a mut region::ScopeTree,
47     param_env: ty::ParamEnv<'tcx>,
48 }
49
50 struct RH<'a> {
51     id: hir::ItemLocalId,
52     sub: &'a [RH<'a>],
53 }
54
55 const EMPTY_SOURCE_STR: &'static str = "#![feature(no_core)] #![no_core]";
56
57 struct ExpectErrorEmitter {
58     messages: Vec<String>,
59 }
60
61 fn remove_message(e: &mut ExpectErrorEmitter, msg: &str, lvl: Level) {
62     match lvl {
63         Level::Bug | Level::Fatal | Level::Error => {}
64         _ => {
65             return;
66         }
67     }
68
69     debug!("Error: {}", msg);
70     match e.messages.iter().position(|m| msg.contains(m)) {
71         Some(i) => {
72             e.messages.remove(i);
73         }
74         None => {
75             debug!("Unexpected error: {} Expected: {:?}", msg, e.messages);
76             panic!("Unexpected error: {} Expected: {:?}", msg, e.messages);
77         }
78     }
79 }
80
81 impl Emitter for ExpectErrorEmitter {
82     fn emit(&mut self, db: &DiagnosticBuilder) {
83         remove_message(self, &db.message(), db.level);
84         for child in &db.children {
85             remove_message(self, &child.message(), child.level);
86         }
87     }
88 }
89
90 fn errors(msgs: &[&str]) -> (Box<Emitter + Send>, usize) {
91     let v = msgs.iter().map(|m| m.to_string()).collect();
92     (box ExpectErrorEmitter { messages: v } as Box<Emitter + Send>, msgs.len())
93 }
94
95 fn test_env<F>(source_string: &str,
96                (emitter, expected_err_count): (Box<Emitter + Send>, usize),
97                body: F)
98     where F: FnOnce(Env)
99 {
100     let mut options = config::basic_options();
101     options.debugging_opts.verbose = true;
102     options.unstable_features = UnstableFeatures::Allow;
103     let diagnostic_handler = errors::Handler::with_emitter(true, false, emitter);
104
105     let dep_graph = DepGraph::new(false);
106     let _ignore = dep_graph.in_ignore();
107     let cstore = Rc::new(CStore::new(box ::MetadataLoader));
108     let sess = session::build_session_(options,
109                                        &dep_graph,
110                                        None,
111                                        diagnostic_handler,
112                                        Rc::new(CodeMap::new(FilePathMapping::empty())));
113     rustc_trans::init(&sess);
114     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
115     let input = config::Input::Str {
116         name: driver::anon_src(),
117         input: source_string.to_string(),
118     };
119     let krate = driver::phase_1_parse_input(&driver::CompileController::basic(),
120                                             &sess,
121                                             &input).unwrap();
122     let driver::ExpansionResult { defs, resolutions, mut hir_forest, .. } = {
123         driver::phase_2_configure_and_expand(&sess,
124                                              &cstore,
125                                              krate,
126                                              None,
127                                              "test",
128                                              None,
129                                              MakeGlobMap::No,
130                                              |_| Ok(()))
131             .expect("phase 2 aborted")
132     };
133     let _ignore = dep_graph.in_ignore();
134
135     let arena = DroplessArena::new();
136     let arenas = ty::GlobalArenas::new();
137     let hir_map = hir_map::map_crate(&mut hir_forest, defs);
138
139     // run just enough stuff to build a tcx:
140     let named_region_map = resolve_lifetime::krate(&sess, &*cstore, &hir_map);
141     TyCtxt::create_and_enter(&sess,
142                              &*cstore,
143                              ty::maps::Providers::default(),
144                              ty::maps::Providers::default(),
145                              Rc::new(Passes::new()),
146                              &arenas,
147                              &arena,
148                              resolutions,
149                              named_region_map.unwrap(),
150                              hir_map,
151                              "test_crate",
152                              |tcx| {
153         tcx.infer_ctxt().enter(|infcx| {
154             let mut region_scope_tree = region::ScopeTree::default();
155             body(Env {
156                 infcx: &infcx,
157                 region_scope_tree: &mut region_scope_tree,
158                 param_env: ty::ParamEnv::empty(Reveal::UserFacing),
159             });
160             let free_regions = FreeRegionMap::new();
161             let def_id = tcx.hir.local_def_id(ast::CRATE_NODE_ID);
162             infcx.resolve_regions_and_report_errors(def_id, &region_scope_tree, &free_regions);
163             assert_eq!(tcx.sess.err_count(), expected_err_count);
164         });
165     });
166 }
167
168 impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> {
169     pub fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
170         self.infcx.tcx
171     }
172
173     pub fn create_region_hierarchy(&mut self, rh: &RH, parent: region::Scope) {
174         let me = region::Scope::Node(rh.id);
175         self.region_scope_tree.record_scope_parent(me, Some(parent));
176         for child_rh in rh.sub {
177             self.create_region_hierarchy(child_rh, me);
178         }
179     }
180
181     pub fn create_simple_region_hierarchy(&mut self) {
182         // creates a region hierarchy where 1 is root, 10 and 11 are
183         // children of 1, etc
184
185         let dscope = region::Scope::Destruction(hir::ItemLocalId(1));
186         self.region_scope_tree.record_scope_parent(dscope, None);
187         self.create_region_hierarchy(&RH {
188             id: hir::ItemLocalId(1),
189             sub: &[RH {
190                 id: hir::ItemLocalId(10),
191                 sub: &[],
192             },
193             RH {
194                 id: hir::ItemLocalId(11),
195                 sub: &[],
196             }],
197         }, dscope);
198     }
199
200     #[allow(dead_code)] // this seems like it could be useful, even if we don't use it now
201     pub fn lookup_item(&self, names: &[String]) -> ast::NodeId {
202         return match search_mod(self, &self.infcx.tcx.hir.krate().module, 0, names) {
203             Some(id) => id,
204             None => {
205                 panic!("no item found: `{}`", names.join("::"));
206             }
207         };
208
209         fn search_mod(this: &Env,
210                       m: &hir::Mod,
211                       idx: usize,
212                       names: &[String])
213                       -> Option<ast::NodeId> {
214             assert!(idx < names.len());
215             for item in &m.item_ids {
216                 let item = this.infcx.tcx.hir.expect_item(item.id);
217                 if item.name.to_string() == names[idx] {
218                     return search(this, item, idx + 1, names);
219                 }
220             }
221             return None;
222         }
223
224         fn search(this: &Env, it: &hir::Item, idx: usize, names: &[String]) -> Option<ast::NodeId> {
225             if idx == names.len() {
226                 return Some(it.id);
227             }
228
229             return match it.node {
230                 hir::ItemUse(..) |
231                 hir::ItemExternCrate(..) |
232                 hir::ItemConst(..) |
233                 hir::ItemStatic(..) |
234                 hir::ItemFn(..) |
235                 hir::ItemForeignMod(..) |
236                 hir::ItemGlobalAsm(..) |
237                 hir::ItemTy(..) => None,
238
239                 hir::ItemEnum(..) |
240                 hir::ItemStruct(..) |
241                 hir::ItemUnion(..) |
242                 hir::ItemTrait(..) |
243                 hir::ItemImpl(..) |
244                 hir::ItemDefaultImpl(..) => None,
245
246                 hir::ItemMod(ref m) => search_mod(this, m, idx, names),
247             };
248         }
249     }
250
251     pub fn make_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
252         match self.infcx.at(&ObligationCause::dummy(), self.param_env).sub(a, b) {
253             Ok(_) => true,
254             Err(ref e) => panic!("Encountered error: {}", e),
255         }
256     }
257
258     pub fn is_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
259         self.infcx.can_sub(self.param_env, a, b).is_ok()
260     }
261
262     pub fn assert_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) {
263         if !self.is_subtype(a, b) {
264             panic!("{} is not a subtype of {}, but it should be", a, b);
265         }
266     }
267
268     pub fn assert_eq(&self, a: Ty<'tcx>, b: Ty<'tcx>) {
269         self.assert_subtype(a, b);
270         self.assert_subtype(b, a);
271     }
272
273     pub fn t_fn(&self, input_tys: &[Ty<'tcx>], output_ty: Ty<'tcx>) -> Ty<'tcx> {
274         self.infcx.tcx.mk_fn_ptr(ty::Binder(self.infcx.tcx.mk_fn_sig(
275             input_tys.iter().cloned(),
276             output_ty,
277             false,
278             hir::Unsafety::Normal,
279             Abi::Rust
280         )))
281     }
282
283     pub fn t_nil(&self) -> Ty<'tcx> {
284         self.infcx.tcx.mk_nil()
285     }
286
287     pub fn t_pair(&self, ty1: Ty<'tcx>, ty2: Ty<'tcx>) -> Ty<'tcx> {
288         self.infcx.tcx.intern_tup(&[ty1, ty2], false)
289     }
290
291     pub fn t_param(&self, index: u32) -> Ty<'tcx> {
292         let name = format!("T{}", index);
293         self.infcx.tcx.mk_param(index, Symbol::intern(&name))
294     }
295
296     pub fn re_early_bound(&self, index: u32, name: &'static str) -> ty::Region<'tcx> {
297         let name = Symbol::intern(name);
298         self.infcx.tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
299             def_id: self.infcx.tcx.hir.local_def_id(ast::CRATE_NODE_ID),
300             index,
301             name,
302         }))
303     }
304
305     pub fn re_late_bound_with_debruijn(&self,
306                                        id: u32,
307                                        debruijn: ty::DebruijnIndex)
308                                        -> ty::Region<'tcx> {
309         self.infcx.tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(id)))
310     }
311
312     pub fn t_rptr(&self, r: ty::Region<'tcx>) -> Ty<'tcx> {
313         self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize)
314     }
315
316     pub fn t_rptr_late_bound(&self, id: u32) -> Ty<'tcx> {
317         let r = self.re_late_bound_with_debruijn(id, ty::DebruijnIndex::new(1));
318         self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize)
319     }
320
321     pub fn t_rptr_late_bound_with_debruijn(&self,
322                                            id: u32,
323                                            debruijn: ty::DebruijnIndex)
324                                            -> Ty<'tcx> {
325         let r = self.re_late_bound_with_debruijn(id, debruijn);
326         self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize)
327     }
328
329     pub fn t_rptr_scope(&self, id: u32) -> Ty<'tcx> {
330         let r = ty::ReScope(region::Scope::Node(hir::ItemLocalId(id)));
331         self.infcx.tcx.mk_imm_ref(self.infcx.tcx.mk_region(r), self.tcx().types.isize)
332     }
333
334     pub fn re_free(&self, id: u32) -> ty::Region<'tcx> {
335         self.infcx.tcx.mk_region(ty::ReFree(ty::FreeRegion {
336             scope: self.infcx.tcx.hir.local_def_id(ast::CRATE_NODE_ID),
337             bound_region: ty::BrAnon(id),
338         }))
339     }
340
341     pub fn t_rptr_free(&self, id: u32) -> Ty<'tcx> {
342         let r = self.re_free(id);
343         self.infcx.tcx.mk_imm_ref(r, self.tcx().types.isize)
344     }
345
346     pub fn t_rptr_static(&self) -> Ty<'tcx> {
347         self.infcx.tcx.mk_imm_ref(self.infcx.tcx.types.re_static,
348                                   self.tcx().types.isize)
349     }
350
351     pub fn t_rptr_empty(&self) -> Ty<'tcx> {
352         self.infcx.tcx.mk_imm_ref(self.infcx.tcx.types.re_empty,
353                                   self.tcx().types.isize)
354     }
355
356     pub fn sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> InferResult<'tcx, ()> {
357         self.infcx.at(&ObligationCause::dummy(), self.param_env).sub(t1, t2)
358     }
359
360     pub fn lub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
361         self.infcx.at(&ObligationCause::dummy(), self.param_env).lub(t1, t2)
362     }
363
364     pub fn glb(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
365         self.infcx.at(&ObligationCause::dummy(), self.param_env).glb(t1, t2)
366     }
367
368     /// Checks that `t1 <: t2` is true (this may register additional
369     /// region checks).
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());
375             }
376             Err(ref e) => {
377                 panic!("unexpected error computing sub({:?},{:?}): {}", t1, t2, e);
378             }
379         }
380     }
381
382     /// Checks that `t1 <: t2` is false (this may register additional
383     /// region checks).
384     pub fn check_not_sub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) {
385         match self.sub(t1, t2) {
386             Err(_) => {}
387             Ok(_) => {
388                 panic!("unexpected success computing sub({:?},{:?})", t1, t2);
389             }
390         }
391     }
392
393     /// Checks that `LUB(t1,t2) == t_lub`
394     pub fn check_lub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>, t_lub: Ty<'tcx>) {
395         match self.lub(t1, t2) {
396             Ok(InferOk { obligations, value: t }) => {
397                 // None of these tests should require nested obligations:
398                 assert!(obligations.is_empty());
399
400                 self.assert_eq(t, t_lub);
401             }
402             Err(ref e) => panic!("unexpected error in LUB: {}", e),
403         }
404     }
405
406     /// Checks that `GLB(t1,t2) == t_glb`
407     pub fn check_glb(&self, t1: Ty<'tcx>, t2: Ty<'tcx>, t_glb: Ty<'tcx>) {
408         debug!("check_glb(t1={}, t2={}, t_glb={})", t1, t2, t_glb);
409         match self.glb(t1, t2) {
410             Err(e) => panic!("unexpected error computing LUB: {:?}", e),
411             Ok(InferOk { obligations, value: t }) => {
412                 // None of these tests should require nested obligations:
413                 assert!(obligations.is_empty());
414
415                 self.assert_eq(t, t_glb);
416
417                 // sanity check for good measure:
418                 self.assert_subtype(t, t1);
419                 self.assert_subtype(t, t2);
420             }
421         }
422     }
423 }
424
425 #[test]
426 fn contravariant_region_ptr_ok() {
427     test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
428         env.create_simple_region_hierarchy();
429         let t_rptr1 = env.t_rptr_scope(1);
430         let t_rptr10 = env.t_rptr_scope(10);
431         env.assert_eq(t_rptr1, t_rptr1);
432         env.assert_eq(t_rptr10, t_rptr10);
433         env.make_subtype(t_rptr1, t_rptr10);
434     })
435 }
436
437 #[test]
438 fn contravariant_region_ptr_err() {
439     test_env(EMPTY_SOURCE_STR, errors(&["mismatched types"]), |mut env| {
440         env.create_simple_region_hierarchy();
441         let t_rptr1 = env.t_rptr_scope(1);
442         let t_rptr10 = env.t_rptr_scope(10);
443         env.assert_eq(t_rptr1, t_rptr1);
444         env.assert_eq(t_rptr10, t_rptr10);
445
446         // will cause an error when regions are resolved
447         env.make_subtype(t_rptr10, t_rptr1);
448     })
449 }
450
451 #[test]
452 fn sub_free_bound_false() {
453     //! Test that:
454     //!
455     //!     fn(&'a isize) <: for<'b> fn(&'b isize)
456     //!
457     //! does NOT hold.
458
459     test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
460         env.create_simple_region_hierarchy();
461         let t_rptr_free1 = env.t_rptr_free(1);
462         let t_rptr_bound1 = env.t_rptr_late_bound(1);
463         env.check_not_sub(env.t_fn(&[t_rptr_free1], env.tcx().types.isize),
464                           env.t_fn(&[t_rptr_bound1], env.tcx().types.isize));
465     })
466 }
467
468 #[test]
469 fn sub_bound_free_true() {
470     //! Test that:
471     //!
472     //!     for<'a> fn(&'a isize) <: fn(&'b isize)
473     //!
474     //! DOES hold.
475
476     test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
477         env.create_simple_region_hierarchy();
478         let t_rptr_bound1 = env.t_rptr_late_bound(1);
479         let t_rptr_free1 = env.t_rptr_free(1);
480         env.check_sub(env.t_fn(&[t_rptr_bound1], env.tcx().types.isize),
481                       env.t_fn(&[t_rptr_free1], env.tcx().types.isize));
482     })
483 }
484
485 #[test]
486 fn sub_free_bound_false_infer() {
487     //! Test that:
488     //!
489     //!     fn(_#1) <: for<'b> fn(&'b isize)
490     //!
491     //! does NOT hold for any instantiation of `_#1`.
492
493     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
494         let t_infer1 = env.infcx.next_ty_var(TypeVariableOrigin::MiscVariable(DUMMY_SP));
495         let t_rptr_bound1 = env.t_rptr_late_bound(1);
496         env.check_not_sub(env.t_fn(&[t_infer1], env.tcx().types.isize),
497                           env.t_fn(&[t_rptr_bound1], env.tcx().types.isize));
498     })
499 }
500
501 #[test]
502 fn lub_free_bound_infer() {
503     //! Test result of:
504     //!
505     //!     LUB(fn(_#1), for<'b> fn(&'b isize))
506     //!
507     //! This should yield `fn(&'_ isize)`. We check
508     //! that it yields `fn(&'x isize)` for some free `'x`,
509     //! anyhow.
510
511     test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
512         env.create_simple_region_hierarchy();
513         let t_infer1 = env.infcx.next_ty_var(TypeVariableOrigin::MiscVariable(DUMMY_SP));
514         let t_rptr_bound1 = env.t_rptr_late_bound(1);
515         let t_rptr_free1 = env.t_rptr_free(1);
516         env.check_lub(env.t_fn(&[t_infer1], env.tcx().types.isize),
517                       env.t_fn(&[t_rptr_bound1], env.tcx().types.isize),
518                       env.t_fn(&[t_rptr_free1], env.tcx().types.isize));
519     });
520 }
521
522 #[test]
523 fn lub_bound_bound() {
524     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
525         let t_rptr_bound1 = env.t_rptr_late_bound(1);
526         let t_rptr_bound2 = env.t_rptr_late_bound(2);
527         env.check_lub(env.t_fn(&[t_rptr_bound1], env.tcx().types.isize),
528                       env.t_fn(&[t_rptr_bound2], env.tcx().types.isize),
529                       env.t_fn(&[t_rptr_bound1], env.tcx().types.isize));
530     })
531 }
532
533 #[test]
534 fn lub_bound_free() {
535     test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
536         env.create_simple_region_hierarchy();
537         let t_rptr_bound1 = env.t_rptr_late_bound(1);
538         let t_rptr_free1 = env.t_rptr_free(1);
539         env.check_lub(env.t_fn(&[t_rptr_bound1], env.tcx().types.isize),
540                       env.t_fn(&[t_rptr_free1], env.tcx().types.isize),
541                       env.t_fn(&[t_rptr_free1], env.tcx().types.isize));
542     })
543 }
544
545 #[test]
546 fn lub_bound_static() {
547     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
548         let t_rptr_bound1 = env.t_rptr_late_bound(1);
549         let t_rptr_static = env.t_rptr_static();
550         env.check_lub(env.t_fn(&[t_rptr_bound1], env.tcx().types.isize),
551                       env.t_fn(&[t_rptr_static], env.tcx().types.isize),
552                       env.t_fn(&[t_rptr_static], env.tcx().types.isize));
553     })
554 }
555
556 #[test]
557 fn lub_bound_bound_inverse_order() {
558     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
559         let t_rptr_bound1 = env.t_rptr_late_bound(1);
560         let t_rptr_bound2 = env.t_rptr_late_bound(2);
561         env.check_lub(env.t_fn(&[t_rptr_bound1, t_rptr_bound2], t_rptr_bound1),
562                       env.t_fn(&[t_rptr_bound2, t_rptr_bound1], t_rptr_bound1),
563                       env.t_fn(&[t_rptr_bound1, t_rptr_bound1], t_rptr_bound1));
564     })
565 }
566
567 #[test]
568 fn lub_free_free() {
569     test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
570         env.create_simple_region_hierarchy();
571         let t_rptr_free1 = env.t_rptr_free(1);
572         let t_rptr_free2 = env.t_rptr_free(2);
573         let t_rptr_static = env.t_rptr_static();
574         env.check_lub(env.t_fn(&[t_rptr_free1], env.tcx().types.isize),
575                       env.t_fn(&[t_rptr_free2], env.tcx().types.isize),
576                       env.t_fn(&[t_rptr_static], env.tcx().types.isize));
577     })
578 }
579
580 #[test]
581 fn lub_returning_scope() {
582     test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
583         env.create_simple_region_hierarchy();
584         let t_rptr_scope10 = env.t_rptr_scope(10);
585         let t_rptr_scope11 = env.t_rptr_scope(11);
586         let t_rptr_empty = env.t_rptr_empty();
587         env.check_lub(env.t_fn(&[t_rptr_scope10], env.tcx().types.isize),
588                       env.t_fn(&[t_rptr_scope11], env.tcx().types.isize),
589                       env.t_fn(&[t_rptr_empty], env.tcx().types.isize));
590     });
591 }
592
593 #[test]
594 fn glb_free_free_with_common_scope() {
595     test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
596         env.create_simple_region_hierarchy();
597         let t_rptr_free1 = env.t_rptr_free(1);
598         let t_rptr_free2 = env.t_rptr_free(2);
599         let t_rptr_scope = env.t_rptr_scope(1);
600         env.check_glb(env.t_fn(&[t_rptr_free1], env.tcx().types.isize),
601                       env.t_fn(&[t_rptr_free2], env.tcx().types.isize),
602                       env.t_fn(&[t_rptr_scope], env.tcx().types.isize));
603     })
604 }
605
606 #[test]
607 fn glb_bound_bound() {
608     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
609         let t_rptr_bound1 = env.t_rptr_late_bound(1);
610         let t_rptr_bound2 = env.t_rptr_late_bound(2);
611         env.check_glb(env.t_fn(&[t_rptr_bound1], env.tcx().types.isize),
612                       env.t_fn(&[t_rptr_bound2], env.tcx().types.isize),
613                       env.t_fn(&[t_rptr_bound1], env.tcx().types.isize));
614     })
615 }
616
617 #[test]
618 fn glb_bound_free() {
619     test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
620         env.create_simple_region_hierarchy();
621         let t_rptr_bound1 = env.t_rptr_late_bound(1);
622         let t_rptr_free1 = env.t_rptr_free(1);
623         env.check_glb(env.t_fn(&[t_rptr_bound1], env.tcx().types.isize),
624                       env.t_fn(&[t_rptr_free1], env.tcx().types.isize),
625                       env.t_fn(&[t_rptr_bound1], env.tcx().types.isize));
626     })
627 }
628
629 #[test]
630 fn glb_bound_free_infer() {
631     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
632         let t_rptr_bound1 = env.t_rptr_late_bound(1);
633         let t_infer1 = env.infcx.next_ty_var(TypeVariableOrigin::MiscVariable(DUMMY_SP));
634
635         // compute GLB(fn(_) -> isize, for<'b> fn(&'b isize) -> isize),
636         // which should yield for<'b> fn(&'b isize) -> isize
637         env.check_glb(env.t_fn(&[t_rptr_bound1], env.tcx().types.isize),
638                       env.t_fn(&[t_infer1], env.tcx().types.isize),
639                       env.t_fn(&[t_rptr_bound1], env.tcx().types.isize));
640
641         // as a side-effect, computing GLB should unify `_` with
642         // `&'_ isize`
643         let t_resolve1 = env.infcx.shallow_resolve(t_infer1);
644         match t_resolve1.sty {
645             ty::TyRef(..) => {}
646             _ => {
647                 panic!("t_resolve1={:?}", t_resolve1);
648             }
649         }
650     })
651 }
652
653 #[test]
654 fn glb_bound_static() {
655     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
656         let t_rptr_bound1 = env.t_rptr_late_bound(1);
657         let t_rptr_static = env.t_rptr_static();
658         env.check_glb(env.t_fn(&[t_rptr_bound1], env.tcx().types.isize),
659                       env.t_fn(&[t_rptr_static], env.tcx().types.isize),
660                       env.t_fn(&[t_rptr_bound1], env.tcx().types.isize));
661     })
662 }
663
664 /// Test substituting a bound region into a function, which introduces another level of binding.
665 /// This requires adjusting the Debruijn index.
666 #[test]
667 fn subst_ty_renumber_bound() {
668
669     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
670         // Situation:
671         // Theta = [A -> &'a foo]
672
673         let t_rptr_bound1 = env.t_rptr_late_bound(1);
674
675         // t_source = fn(A)
676         let t_source = {
677             let t_param = env.t_param(0);
678             env.t_fn(&[t_param], env.t_nil())
679         };
680
681         let substs = env.infcx.tcx.intern_substs(&[Kind::from(t_rptr_bound1)]);
682         let t_substituted = t_source.subst(env.infcx.tcx, substs);
683
684         // t_expected = fn(&'a isize)
685         let t_expected = {
686             let t_ptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
687             env.t_fn(&[t_ptr_bound2], env.t_nil())
688         };
689
690         debug!("subst_bound: t_source={:?} substs={:?} t_substituted={:?} t_expected={:?}",
691                t_source,
692                substs,
693                t_substituted,
694                t_expected);
695
696         assert_eq!(t_substituted, t_expected);
697     })
698 }
699
700 /// Test substituting a bound region into a function, which introduces another level of binding.
701 /// This requires adjusting the Debruijn index.
702 #[test]
703 fn subst_ty_renumber_some_bounds() {
704     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
705         // Situation:
706         // Theta = [A -> &'a foo]
707
708         let t_rptr_bound1 = env.t_rptr_late_bound(1);
709
710         // t_source = (A, fn(A))
711         let t_source = {
712             let t_param = env.t_param(0);
713             env.t_pair(t_param, env.t_fn(&[t_param], env.t_nil()))
714         };
715
716         let substs = env.infcx.tcx.intern_substs(&[Kind::from(t_rptr_bound1)]);
717         let t_substituted = t_source.subst(env.infcx.tcx, substs);
718
719         // t_expected = (&'a isize, fn(&'a isize))
720         //
721         // but not that the Debruijn index is different in the different cases.
722         let t_expected = {
723             let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
724             env.t_pair(t_rptr_bound1, env.t_fn(&[t_rptr_bound2], env.t_nil()))
725         };
726
727         debug!("subst_bound: t_source={:?} substs={:?} t_substituted={:?} t_expected={:?}",
728                t_source,
729                substs,
730                t_substituted,
731                t_expected);
732
733         assert_eq!(t_substituted, t_expected);
734     })
735 }
736
737 /// Test that we correctly compute whether a type has escaping regions or not.
738 #[test]
739 fn escaping() {
740
741     test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| {
742         // Situation:
743         // Theta = [A -> &'a foo]
744         env.create_simple_region_hierarchy();
745
746         assert!(!env.t_nil().has_escaping_regions());
747
748         let t_rptr_free1 = env.t_rptr_free(1);
749         assert!(!t_rptr_free1.has_escaping_regions());
750
751         let t_rptr_bound1 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(1));
752         assert!(t_rptr_bound1.has_escaping_regions());
753
754         let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
755         assert!(t_rptr_bound2.has_escaping_regions());
756
757         // t_fn = fn(A)
758         let t_param = env.t_param(0);
759         assert!(!t_param.has_escaping_regions());
760         let t_fn = env.t_fn(&[t_param], env.t_nil());
761         assert!(!t_fn.has_escaping_regions());
762     })
763 }
764
765 /// Test applying a substitution where the value being substituted for an early-bound region is a
766 /// late-bound region.
767 #[test]
768 fn subst_region_renumber_region() {
769     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
770         let re_bound1 = env.re_late_bound_with_debruijn(1, ty::DebruijnIndex::new(1));
771
772         // type t_source<'a> = fn(&'a isize)
773         let t_source = {
774             let re_early = env.re_early_bound(0, "'a");
775             env.t_fn(&[env.t_rptr(re_early)], env.t_nil())
776         };
777
778         let substs = env.infcx.tcx.intern_substs(&[Kind::from(re_bound1)]);
779         let t_substituted = t_source.subst(env.infcx.tcx, substs);
780
781         // t_expected = fn(&'a isize)
782         //
783         // but not that the Debruijn index is different in the different cases.
784         let t_expected = {
785             let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
786             env.t_fn(&[t_rptr_bound2], env.t_nil())
787         };
788
789         debug!("subst_bound: t_source={:?} substs={:?} t_substituted={:?} t_expected={:?}",
790                t_source,
791                substs,
792                t_substituted,
793                t_expected);
794
795         assert_eq!(t_substituted, t_expected);
796     })
797 }
798
799 #[test]
800 fn walk_ty() {
801     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
802         let tcx = env.infcx.tcx;
803         let int_ty = tcx.types.isize;
804         let usize_ty = tcx.types.usize;
805         let tup1_ty = tcx.intern_tup(&[int_ty, usize_ty, int_ty, usize_ty], false);
806         let tup2_ty = tcx.intern_tup(&[tup1_ty, tup1_ty, usize_ty], false);
807         let walked: Vec<_> = tup2_ty.walk().collect();
808         assert_eq!(walked,
809                    [tup2_ty, tup1_ty, int_ty, usize_ty, int_ty, usize_ty, tup1_ty, int_ty,
810                     usize_ty, int_ty, usize_ty, usize_ty]);
811     })
812 }
813
814 #[test]
815 fn walk_ty_skip_subtree() {
816     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
817         let tcx = env.infcx.tcx;
818         let int_ty = tcx.types.isize;
819         let usize_ty = tcx.types.usize;
820         let tup1_ty = tcx.intern_tup(&[int_ty, usize_ty, int_ty, usize_ty], false);
821         let tup2_ty = tcx.intern_tup(&[tup1_ty, tup1_ty, usize_ty], false);
822
823         // types we expect to see (in order), plus a boolean saying
824         // whether to skip the subtree.
825         let mut expected = vec![(tup2_ty, false),
826                                 (tup1_ty, false),
827                                 (int_ty, false),
828                                 (usize_ty, false),
829                                 (int_ty, false),
830                                 (usize_ty, false),
831                                 (tup1_ty, true), // skip the isize/usize/isize/usize
832                                 (usize_ty, false)];
833         expected.reverse();
834
835         let mut walker = tup2_ty.walk();
836         while let Some(t) = walker.next() {
837             debug!("walked to {:?}", t);
838             let (expected_ty, skip) = expected.pop().unwrap();
839             assert_eq!(t, expected_ty);
840             if skip {
841                 walker.skip_current_subtree();
842             }
843         }
844
845         assert!(expected.is_empty());
846     })
847 }