]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/test.rs
1e8c1fd14787d240f1a35f1991b43641710f6e4c
[rust.git] / src / librustc_trans / 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 /*!
12
13 # Standalone Tests for the Inference Module
14
15 */
16
17 use driver::diagnostic;
18 use driver::diagnostic::Emitter;
19 use driver::driver;
20 use middle::lang_items;
21 use middle::region::{mod, CodeExtent};
22 use middle::resolve;
23 use middle::resolve_lifetime;
24 use middle::stability;
25 use middle::subst;
26 use middle::subst::Subst;
27 use middle::ty::{mod, Ty};
28 use middle::typeck::infer::combine::Combine;
29 use middle::typeck::infer;
30 use middle::typeck::infer::lub::Lub;
31 use middle::typeck::infer::glb::Glb;
32 use session::{mod,config};
33 use syntax::{abi, ast, ast_map, ast_util};
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 util::ppaux::{ty_to_string, Repr, UserString};
39
40 use arena::TypedArena;
41
42 struct Env<'a, 'tcx: 'a> {
43     infcx: &'a infer::InferCtxt<'a, 'tcx>,
44 }
45
46 struct RH<'a> {
47     id: ast::NodeId,
48     sub: &'a [RH<'a>]
49 }
50
51 static EMPTY_SOURCE_STR: &'static str = "#![no_std]";
52
53 struct ExpectErrorEmitter {
54     messages: Vec<String>
55 }
56
57 fn remove_message(e: &mut ExpectErrorEmitter, msg: &str, lvl: Level) {
58     match lvl {
59         Bug | Fatal | Error => { }
60         Warning | Note | Help => { return; }
61     }
62
63     debug!("Error: {}", msg);
64     match e.messages.iter().position(|m| msg.contains(m.as_slice())) {
65         Some(i) => {
66             e.messages.remove(i);
67         }
68         None => {
69             panic!("Unexpected error: {} Expected: {}",
70                   msg, e.messages);
71         }
72     }
73 }
74
75 impl Emitter for ExpectErrorEmitter {
76     fn emit(&mut self,
77             _cmsp: Option<(&codemap::CodeMap, Span)>,
78             msg: &str,
79             _: Option<&str>,
80             lvl: Level)
81     {
82         remove_message(self, msg, lvl);
83     }
84
85     fn custom_emit(&mut self,
86                    _cm: &codemap::CodeMap,
87                    _sp: RenderSpan,
88                    msg: &str,
89                    lvl: Level)
90     {
91         remove_message(self, msg, lvl);
92     }
93 }
94
95 fn errors(msgs: &[&str]) -> (Box<Emitter+Send>, uint) {
96     let v = msgs.iter().map(|m| m.to_string()).collect();
97     (box ExpectErrorEmitter { messages: v } as Box<Emitter+Send>, msgs.len())
98 }
99
100 fn test_env(source_string: &str,
101             (emitter, expected_err_count): (Box<Emitter+Send>, uint),
102             body: |Env|) {
103     let mut options =
104         config::basic_options();
105     options.debugging_opts |= config::VERBOSE;
106     let codemap =
107         CodeMap::new();
108     let diagnostic_handler =
109         diagnostic::mk_handler(emitter);
110     let span_diagnostic_handler =
111         diagnostic::mk_span_handler(diagnostic_handler, codemap);
112
113     let sess = session::build_session_(options, None, span_diagnostic_handler);
114     let krate_config = Vec::new();
115     let input = driver::StrInput(source_string.to_string());
116     let krate = driver::phase_1_parse_input(&sess, krate_config, &input);
117     let krate = driver::phase_2_configure_and_expand(&sess, krate, "test", None)
118                     .expect("phase 2 aborted");
119
120     let mut forest = ast_map::Forest::new(krate);
121     let ast_map = driver::assign_node_ids_and_map(&sess, &mut forest);
122     let krate = ast_map.krate();
123
124     // run just enough stuff to build a tcx:
125     let lang_items = lang_items::collect_language_items(krate, &sess);
126     let resolve::CrateMap { def_map, freevars, capture_mode_map, .. } =
127         resolve::resolve_crate(&sess, &lang_items, krate);
128     let named_region_map = resolve_lifetime::krate(&sess, krate, &def_map);
129     let region_map = region::resolve_crate(&sess, krate);
130     let stability_index = stability::Index::build(krate);
131     let type_arena = TypedArena::new();
132     let tcx = ty::mk_ctxt(sess,
133                           &type_arena,
134                           def_map,
135                           named_region_map,
136                           ast_map,
137                           freevars,
138                           capture_mode_map,
139                           region_map,
140                           lang_items,
141                           stability_index);
142     let infcx = infer::new_infer_ctxt(&tcx);
143     body(Env { infcx: &infcx });
144     infcx.resolve_regions_and_report_errors();
145     assert_eq!(tcx.sess.err_count(), expected_err_count);
146 }
147
148 impl<'a, 'tcx> Env<'a, 'tcx> {
149     pub fn create_region_hierarchy(&self, rh: &RH) {
150         for child_rh in rh.sub.iter() {
151             self.create_region_hierarchy(child_rh);
152             self.infcx.tcx.region_maps.record_encl_scope(
153                 CodeExtent::from_node_id(child_rh.id),
154                 CodeExtent::from_node_id(rh.id));
155         }
156     }
157
158     pub fn create_simple_region_hierarchy(&self) {
159         // creates a region hierarchy where 1 is root, 10 and 11 are
160         // children of 1, etc
161         self.create_region_hierarchy(
162             &RH {id: 1,
163                  sub: &[RH {id: 10,
164                             sub: &[]},
165                         RH {id: 11,
166                             sub: &[]}]});
167     }
168
169     #[allow(dead_code)] // this seems like it could be useful, even if we don't use it now
170     pub fn lookup_item(&self, names: &[String]) -> ast::NodeId {
171         return match search_mod(self, &self.infcx.tcx.map.krate().module, 0, names) {
172             Some(id) => id,
173             None => {
174                 panic!("no item found: `{}`", names.connect("::"));
175             }
176         };
177
178         fn search_mod(this: &Env,
179                       m: &ast::Mod,
180                       idx: uint,
181                       names: &[String])
182                       -> Option<ast::NodeId> {
183             assert!(idx < names.len());
184             for item in m.items.iter() {
185                 if item.ident.user_string(this.infcx.tcx) == names[idx] {
186                     return search(this, &**item, idx+1, names);
187                 }
188             }
189             return None;
190         }
191
192         fn search(this: &Env,
193                   it: &ast::Item,
194                   idx: uint,
195                   names: &[String])
196                   -> Option<ast::NodeId> {
197             if idx == names.len() {
198                 return Some(it.id);
199             }
200
201             return match it.node {
202                 ast::ItemConst(..) | ast::ItemStatic(..) | ast::ItemFn(..) |
203                 ast::ItemForeignMod(..) | ast::ItemTy(..) => {
204                     None
205                 }
206
207                 ast::ItemEnum(..) | ast::ItemStruct(..) |
208                 ast::ItemTrait(..) | ast::ItemImpl(..) |
209                 ast::ItemMac(..) => {
210                     None
211                 }
212
213                 ast::ItemMod(ref m) => {
214                     search_mod(this, m, idx, names)
215                 }
216             };
217         }
218     }
219
220     pub fn make_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
221         match infer::mk_subty(self.infcx, true, infer::Misc(DUMMY_SP), a, b) {
222             Ok(_) => true,
223             Err(ref e) => panic!("Encountered error: {}",
224                                 ty::type_err_to_str(self.infcx.tcx, e))
225         }
226     }
227
228     pub fn is_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
229         match infer::can_mk_subty(self.infcx, a, b) {
230             Ok(_) => true,
231             Err(_) => false
232         }
233     }
234
235     pub fn assert_subtype(&self, a: Ty<'tcx>, b: Ty<'tcx>) {
236         if !self.is_subtype(a, b) {
237             panic!("{} is not a subtype of {}, but it should be",
238                   self.ty_to_string(a),
239                   self.ty_to_string(b));
240         }
241     }
242
243     pub fn assert_eq(&self, a: Ty<'tcx>, b: Ty<'tcx>) {
244         self.assert_subtype(a, b);
245         self.assert_subtype(b, a);
246     }
247
248     pub fn ty_to_string(&self, a: Ty<'tcx>) -> String {
249         ty_to_string(self.infcx.tcx, a)
250     }
251
252     pub fn t_fn(&self,
253                 input_tys: &[Ty<'tcx>],
254                 output_ty: Ty<'tcx>)
255                 -> Ty<'tcx>
256     {
257         ty::mk_ctor_fn(self.infcx.tcx, input_tys, output_ty)
258     }
259
260     pub fn t_nil(&self) -> Ty<'tcx> {
261         ty::mk_nil(self.infcx.tcx)
262     }
263
264     pub fn t_pair(&self, ty1: Ty<'tcx>, ty2: Ty<'tcx>) -> Ty<'tcx> {
265         ty::mk_tup(self.infcx.tcx, vec![ty1, ty2])
266     }
267
268     pub fn t_closure(&self,
269                      input_tys: &[Ty<'tcx>],
270                      output_ty: Ty<'tcx>,
271                      region_bound: ty::Region)
272                      -> Ty<'tcx>
273     {
274         ty::mk_closure(self.infcx.tcx, ty::ClosureTy {
275             fn_style: ast::NormalFn,
276             onceness: ast::Many,
277             store: ty::RegionTraitStore(region_bound, ast::MutMutable),
278             bounds: ty::region_existential_bound(region_bound),
279             sig: ty::FnSig {
280                 inputs: input_tys.to_vec(),
281                 output: ty::FnConverging(output_ty),
282                 variadic: false,
283             },
284             abi: abi::Rust,
285         })
286     }
287
288     pub fn t_param(&self, space: subst::ParamSpace, index: uint) -> Ty<'tcx> {
289         ty::mk_param(self.infcx.tcx, space, index, ast_util::local_def(ast::DUMMY_NODE_ID))
290     }
291
292     pub fn re_early_bound(&self,
293                           space: subst::ParamSpace,
294                           index: uint,
295                           name: &'static str)
296                           -> ty::Region
297     {
298         let name = token::intern(name);
299         ty::ReEarlyBound(ast::DUMMY_NODE_ID, space, index, name)
300     }
301
302     pub fn re_late_bound_with_debruijn(&self, id: uint, debruijn: ty::DebruijnIndex) -> ty::Region {
303         ty::ReLateBound(debruijn, ty::BrAnon(id))
304     }
305
306     pub fn t_rptr(&self, r: ty::Region) -> Ty<'tcx> {
307         ty::mk_imm_rptr(self.infcx.tcx, r, ty::mk_int())
308     }
309
310     pub fn t_rptr_late_bound(&self, id: uint) -> Ty<'tcx> {
311         ty::mk_imm_rptr(self.infcx.tcx,
312                         self.re_late_bound_with_debruijn(id, ty::DebruijnIndex::new(1)),
313                         ty::mk_int())
314     }
315
316     pub fn t_rptr_late_bound_with_debruijn(&self,
317                                            id: uint,
318                                            debruijn: ty::DebruijnIndex)
319                                            -> Ty<'tcx> {
320         ty::mk_imm_rptr(self.infcx.tcx,
321                         self.re_late_bound_with_debruijn(id, debruijn),
322                         ty::mk_int())
323     }
324
325     pub fn t_rptr_scope(&self, id: ast::NodeId) -> Ty<'tcx> {
326         ty::mk_imm_rptr(self.infcx.tcx, ty::ReScope(CodeExtent::from_node_id(id)), ty::mk_int())
327     }
328
329     pub fn re_free(&self, nid: ast::NodeId, id: uint) -> ty::Region {
330         ty::ReFree(ty::FreeRegion { scope: CodeExtent::from_node_id(nid),
331                                     bound_region: ty::BrAnon(id)})
332     }
333
334     pub fn t_rptr_free(&self, nid: ast::NodeId, id: uint) -> Ty<'tcx> {
335         ty::mk_imm_rptr(self.infcx.tcx, self.re_free(nid, id), ty::mk_int())
336     }
337
338     pub fn t_rptr_static(&self) -> Ty<'tcx> {
339         ty::mk_imm_rptr(self.infcx.tcx, ty::ReStatic, ty::mk_int())
340     }
341
342     pub fn dummy_type_trace(&self) -> infer::TypeTrace<'tcx> {
343         infer::TypeTrace::dummy()
344     }
345
346     pub fn lub(&self) -> Lub<'a, 'tcx> {
347         let trace = self.dummy_type_trace();
348         Lub(self.infcx.combine_fields(true, trace))
349     }
350
351     pub fn glb(&self) -> Glb<'a, 'tcx> {
352         let trace = self.dummy_type_trace();
353         Glb(self.infcx.combine_fields(true, trace))
354     }
355
356     pub fn make_lub_ty(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> Ty<'tcx> {
357         match self.lub().tys(t1, t2) {
358             Ok(t) => t,
359             Err(ref e) => panic!("unexpected error computing LUB: {}",
360                                 ty::type_err_to_str(self.infcx.tcx, e))
361         }
362     }
363
364     /// Checks that `LUB(t1,t2) == t_lub`
365     pub fn check_lub(&self, t1: Ty<'tcx>, t2: Ty<'tcx>, t_lub: Ty<'tcx>) {
366         match self.lub().tys(t1, t2) {
367             Ok(t) => {
368                 self.assert_eq(t, t_lub);
369             }
370             Err(ref e) => {
371                 panic!("unexpected error in LUB: {}",
372                       ty::type_err_to_str(self.infcx.tcx, e))
373             }
374         }
375     }
376
377     /// Checks that `GLB(t1,t2) == t_glb`
378     pub fn check_glb(&self, t1: Ty<'tcx>, t2: Ty<'tcx>, t_glb: Ty<'tcx>) {
379         debug!("check_glb(t1={}, t2={}, t_glb={})",
380                self.ty_to_string(t1),
381                self.ty_to_string(t2),
382                self.ty_to_string(t_glb));
383         match self.glb().tys(t1, t2) {
384             Err(e) => {
385                 panic!("unexpected error computing LUB: {}", e)
386             }
387             Ok(t) => {
388                 self.assert_eq(t, t_glb);
389
390                 // sanity check for good measure:
391                 self.assert_subtype(t, t1);
392                 self.assert_subtype(t, t2);
393             }
394         }
395     }
396 }
397
398 #[test]
399 fn contravariant_region_ptr_ok() {
400     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
401         env.create_simple_region_hierarchy();
402         let t_rptr1 = env.t_rptr_scope(1);
403         let t_rptr10 = env.t_rptr_scope(10);
404         env.assert_eq(t_rptr1, t_rptr1);
405         env.assert_eq(t_rptr10, t_rptr10);
406         env.make_subtype(t_rptr1, t_rptr10);
407     })
408 }
409
410 #[test]
411 fn contravariant_region_ptr_err() {
412     test_env(EMPTY_SOURCE_STR,
413              errors(&["lifetime mismatch"]),
414              |env| {
415                  env.create_simple_region_hierarchy();
416                  let t_rptr1 = env.t_rptr_scope(1);
417                  let t_rptr10 = env.t_rptr_scope(10);
418                  env.assert_eq(t_rptr1, t_rptr1);
419                  env.assert_eq(t_rptr10, t_rptr10);
420
421                  // will cause an error when regions are resolved
422                  env.make_subtype(t_rptr10, t_rptr1);
423              })
424 }
425
426 #[test]
427 fn lub_bound_bound() {
428     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
429         let t_rptr_bound1 = env.t_rptr_late_bound(1);
430         let t_rptr_bound2 = env.t_rptr_late_bound(2);
431         env.check_lub(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
432                       env.t_fn(&[t_rptr_bound2], ty::mk_int()),
433                       env.t_fn(&[t_rptr_bound1], ty::mk_int()));
434     })
435 }
436
437 #[test]
438 fn lub_bound_free() {
439     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
440         let t_rptr_bound1 = env.t_rptr_late_bound(1);
441         let t_rptr_free1 = env.t_rptr_free(0, 1);
442         env.check_lub(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
443                       env.t_fn(&[t_rptr_free1], ty::mk_int()),
444                       env.t_fn(&[t_rptr_free1], ty::mk_int()));
445     })
446 }
447
448 #[test]
449 fn lub_bound_static() {
450     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
451         let t_rptr_bound1 = env.t_rptr_late_bound(1);
452         let t_rptr_static = env.t_rptr_static();
453         env.check_lub(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
454                       env.t_fn(&[t_rptr_static], ty::mk_int()),
455                       env.t_fn(&[t_rptr_static], ty::mk_int()));
456     })
457 }
458
459 #[test]
460 fn lub_bound_bound_inverse_order() {
461     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
462         let t_rptr_bound1 = env.t_rptr_late_bound(1);
463         let t_rptr_bound2 = env.t_rptr_late_bound(2);
464         env.check_lub(env.t_fn(&[t_rptr_bound1, t_rptr_bound2], t_rptr_bound1),
465                       env.t_fn(&[t_rptr_bound2, t_rptr_bound1], t_rptr_bound1),
466                       env.t_fn(&[t_rptr_bound1, t_rptr_bound1], t_rptr_bound1));
467     })
468 }
469
470 #[test]
471 fn lub_free_free() {
472     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
473         let t_rptr_free1 = env.t_rptr_free(0, 1);
474         let t_rptr_free2 = env.t_rptr_free(0, 2);
475         let t_rptr_static = env.t_rptr_static();
476         env.check_lub(env.t_fn(&[t_rptr_free1], ty::mk_int()),
477                       env.t_fn(&[t_rptr_free2], ty::mk_int()),
478                       env.t_fn(&[t_rptr_static], ty::mk_int()));
479     })
480 }
481
482 #[test]
483 fn lub_returning_scope() {
484     test_env(EMPTY_SOURCE_STR,
485              errors(&["cannot infer an appropriate lifetime"]), |env| {
486                  let t_rptr_scope10 = env.t_rptr_scope(10);
487                  let t_rptr_scope11 = env.t_rptr_scope(11);
488
489                  // this should generate an error when regions are resolved
490                  env.make_lub_ty(env.t_fn(&[], t_rptr_scope10),
491                                  env.t_fn(&[], t_rptr_scope11));
492              })
493 }
494
495 #[test]
496 fn glb_free_free_with_common_scope() {
497     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
498         let t_rptr_free1 = env.t_rptr_free(0, 1);
499         let t_rptr_free2 = env.t_rptr_free(0, 2);
500         let t_rptr_scope = env.t_rptr_scope(0);
501         env.check_glb(env.t_fn(&[t_rptr_free1], ty::mk_int()),
502                       env.t_fn(&[t_rptr_free2], ty::mk_int()),
503                       env.t_fn(&[t_rptr_scope], ty::mk_int()));
504     })
505 }
506
507 #[test]
508 fn glb_bound_bound() {
509     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
510         let t_rptr_bound1 = env.t_rptr_late_bound(1);
511         let t_rptr_bound2 = env.t_rptr_late_bound(2);
512         env.check_glb(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
513                       env.t_fn(&[t_rptr_bound2], ty::mk_int()),
514                       env.t_fn(&[t_rptr_bound1], ty::mk_int()));
515     })
516 }
517
518 #[test]
519 fn glb_bound_free() {
520     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
521         let t_rptr_bound1 = env.t_rptr_late_bound(1);
522         let t_rptr_free1 = env.t_rptr_free(0, 1);
523         env.check_glb(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
524                       env.t_fn(&[t_rptr_free1], ty::mk_int()),
525                       env.t_fn(&[t_rptr_bound1], ty::mk_int()));
526     })
527 }
528
529 #[test]
530 fn glb_bound_static() {
531     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
532         let t_rptr_bound1 = env.t_rptr_late_bound(1);
533         let t_rptr_static = env.t_rptr_static();
534         env.check_glb(env.t_fn(&[t_rptr_bound1], ty::mk_int()),
535                       env.t_fn(&[t_rptr_static], ty::mk_int()),
536                       env.t_fn(&[t_rptr_bound1], ty::mk_int()));
537     })
538 }
539
540 #[test]
541 fn subst_ty_renumber_bound() {
542     /*!
543      * Test substituting a bound region into a function, which introduces another
544      * level of binding. This requires adjusting the Debruijn index.
545      */
546
547     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
548         // Situation:
549         // Theta = [A -> &'a foo]
550
551         let t_rptr_bound1 = env.t_rptr_late_bound(1);
552
553         // t_source = fn(A)
554         let t_source = {
555             let t_param = env.t_param(subst::TypeSpace, 0);
556             env.t_fn(&[t_param], env.t_nil())
557         };
558
559         let substs = subst::Substs::new_type(vec![t_rptr_bound1], vec![]);
560         let t_substituted = t_source.subst(env.infcx.tcx, &substs);
561
562         // t_expected = fn(&'a int)
563         let t_expected = {
564             let t_ptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
565             env.t_fn(&[t_ptr_bound2], env.t_nil())
566         };
567
568         debug!("subst_bound: t_source={} substs={} t_substituted={} t_expected={}",
569                t_source.repr(env.infcx.tcx),
570                substs.repr(env.infcx.tcx),
571                t_substituted.repr(env.infcx.tcx),
572                t_expected.repr(env.infcx.tcx));
573
574         assert_eq!(t_substituted, t_expected);
575     })
576 }
577
578 #[test]
579 fn subst_ty_renumber_some_bounds() {
580     /*!
581      * Test substituting a bound region into a function, which introduces another
582      * level of binding. This requires adjusting the Debruijn index.
583      */
584
585     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
586         // Situation:
587         // Theta = [A -> &'a foo]
588
589         let t_rptr_bound1 = env.t_rptr_late_bound(1);
590
591         // t_source = (A, fn(A))
592         let t_source = {
593             let t_param = env.t_param(subst::TypeSpace, 0);
594             env.t_pair(t_param, env.t_fn(&[t_param], env.t_nil()))
595         };
596
597         let substs = subst::Substs::new_type(vec![t_rptr_bound1], vec![]);
598         let t_substituted = t_source.subst(env.infcx.tcx, &substs);
599
600         // t_expected = (&'a int, fn(&'a int))
601         //
602         // but not that the Debruijn index is different in the different cases.
603         let t_expected = {
604             let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
605             env.t_pair(t_rptr_bound1, env.t_fn(&[t_rptr_bound2], env.t_nil()))
606         };
607
608         debug!("subst_bound: t_source={} substs={} t_substituted={} t_expected={}",
609                t_source.repr(env.infcx.tcx),
610                substs.repr(env.infcx.tcx),
611                t_substituted.repr(env.infcx.tcx),
612                t_expected.repr(env.infcx.tcx));
613
614         assert_eq!(t_substituted, t_expected);
615     })
616 }
617
618 #[test]
619 fn escaping() {
620     /*!
621      * Test that we correctly compute whether a type has escaping
622      * regions or not.
623      */
624
625     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
626         // Situation:
627         // Theta = [A -> &'a foo]
628
629         assert!(!ty::type_has_escaping_regions(env.t_nil()));
630
631         let t_rptr_free1 = env.t_rptr_free(0, 1);
632         assert!(!ty::type_has_escaping_regions(t_rptr_free1));
633
634         let t_rptr_bound1 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(1));
635         assert!(ty::type_has_escaping_regions(t_rptr_bound1));
636
637         let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
638         assert!(ty::type_has_escaping_regions(t_rptr_bound2));
639
640         // t_fn = fn(A)
641         let t_param = env.t_param(subst::TypeSpace, 0);
642         assert!(!ty::type_has_escaping_regions(t_param));
643         let t_fn = env.t_fn(&[t_param], env.t_nil());
644         assert!(!ty::type_has_escaping_regions(t_fn));
645
646         // t_fn = |&int|+'a
647         let t_fn = env.t_closure(&[t_rptr_bound1], env.t_nil(), env.re_free(0, 1));
648         assert!(!ty::type_has_escaping_regions(t_fn));
649
650         // t_fn = |&int|+'a (where &int has depth 2)
651         let t_fn = env.t_closure(&[t_rptr_bound2], env.t_nil(), env.re_free(0, 1));
652         assert!(ty::type_has_escaping_regions(t_fn));
653
654         // t_fn = |&int|+&int
655         let t_fn = env.t_closure(&[t_rptr_bound1], env.t_nil(),
656                                  env.re_late_bound_with_debruijn(1, ty::DebruijnIndex::new(1)));
657         assert!(ty::type_has_escaping_regions(t_fn));
658     })
659 }
660
661 #[test]
662 fn subst_region_renumber_region() {
663     /*!
664      * Test applying a substitution where the value being substituted
665      * for an early-bound region is a late-bound region.
666      */
667
668     test_env(EMPTY_SOURCE_STR, errors(&[]), |env| {
669         let re_bound1 = env.re_late_bound_with_debruijn(1, ty::DebruijnIndex::new(1));
670
671         // type t_source<'a> = fn(&'a int)
672         let t_source = {
673             let re_early = env.re_early_bound(subst::TypeSpace, 0, "'a");
674             env.t_fn(&[env.t_rptr(re_early)], env.t_nil())
675         };
676
677         let substs = subst::Substs::new_type(vec![], vec![re_bound1]);
678         let t_substituted = t_source.subst(env.infcx.tcx, &substs);
679
680         // t_expected = fn(&'a int)
681         //
682         // but not that the Debruijn index is different in the different cases.
683         let t_expected = {
684             let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, ty::DebruijnIndex::new(2));
685             env.t_fn(&[t_rptr_bound2], env.t_nil())
686         };
687
688         debug!("subst_bound: t_source={} substs={} t_substituted={} t_expected={}",
689                t_source.repr(env.infcx.tcx),
690                substs.repr(env.infcx.tcx),
691                t_substituted.repr(env.infcx.tcx),
692                t_expected.repr(env.infcx.tcx));
693
694         assert_eq!(t_substituted, t_expected);
695     })
696 }
697