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