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