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