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