-
Notifications
You must be signed in to change notification settings - Fork 12.1k
/
combine.rs
687 lines (603 loc) · 24.5 KB
/
combine.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
///////////////////////////////////////////////////////////////////////////
// # Type combining
//
// There are four type combiners: equate, sub, lub, and glb. Each
// implements the trait `Combine` and contains methods for combining
// two instances of various things and yielding a new instance. These
// combiner methods always yield a `Result<T>`. There is a lot of
// common code for these operations, implemented as default methods on
// the `Combine` trait.
//
// Each operation may have side-effects on the inference context,
// though these can be unrolled using snapshots. On success, the
// LUB/GLB operations return the appropriate bound. The Eq and Sub
// operations generally return the first operand.
//
// ## Contravariance
//
// When you are relating two things which have a contravariant
// relationship, you should use `contratys()` or `contraregions()`,
// rather than inversing the order of arguments! This is necessary
// because the order of arguments is not relevant for LUB and GLB. It
// is also useful to track which value is the "expected" value in
// terms of error reporting.
use middle::subst;
use middle::subst::Substs;
use middle::ty::{FloatVar, FnSig, IntVar, TyVar};
use middle::ty::{IntType, UintType};
use middle::ty::{BuiltinBounds};
use middle::ty;
use middle::typeck::infer::equate::Equate;
use middle::typeck::infer::glb::Glb;
use middle::typeck::infer::lub::Lub;
use middle::typeck::infer::sub::Sub;
use middle::typeck::infer::unify::InferCtxtMethodsForSimplyUnifiableTypes;
use middle::typeck::infer::{InferCtxt, cres};
use middle::typeck::infer::{MiscVariable, TypeTrace};
use middle::typeck::infer::type_variable::{RelationDir, EqTo,
SubtypeOf, SupertypeOf};
use middle::ty_fold::{RegionFolder, TypeFoldable};
use util::ppaux::Repr;
use std::result;
use syntax::ast::{Onceness, FnStyle};
use syntax::ast;
use syntax::abi;
pub trait Combine {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a>;
fn tag(&self) -> String;
fn a_is_expected(&self) -> bool;
fn trace(&self) -> TypeTrace;
fn equate<'a>(&'a self) -> Equate<'a>;
fn sub<'a>(&'a self) -> Sub<'a>;
fn lub<'a>(&'a self) -> Lub<'a>;
fn glb<'a>(&'a self) -> Glb<'a>;
fn mts(&self, a: &ty::mt, b: &ty::mt) -> cres<ty::mt>;
fn contratys(&self, a: ty::t, b: ty::t) -> cres<ty::t>;
fn tys(&self, a: ty::t, b: ty::t) -> cres<ty::t>;
fn tps(&self,
_: subst::ParamSpace,
as_: &[ty::t],
bs: &[ty::t])
-> cres<Vec<ty::t>> {
// FIXME -- In general, we treat variance a bit wrong
// here. For historical reasons, we treat tps and Self
// as invariant. This is overly conservative.
if as_.len() != bs.len() {
return Err(ty::terr_ty_param_size(expected_found(self,
as_.len(),
bs.len())));
}
try!(result::fold_(as_
.iter()
.zip(bs.iter())
.map(|(a, b)| self.equate().tys(*a, *b))));
Ok(Vec::from_slice(as_))
}
fn substs(&self,
item_def_id: ast::DefId,
a_subst: &subst::Substs,
b_subst: &subst::Substs)
-> cres<subst::Substs>
{
let variances = if self.infcx().tcx.variance_computed.get() {
Some(ty::item_variances(self.infcx().tcx, item_def_id))
} else {
None
};
let mut substs = subst::Substs::empty();
for &space in subst::ParamSpace::all().iter() {
let a_tps = a_subst.types.get_slice(space);
let b_tps = b_subst.types.get_slice(space);
let tps = try!(self.tps(space, a_tps, b_tps));
let a_regions = a_subst.regions().get_slice(space);
let b_regions = b_subst.regions().get_slice(space);
let mut invariance = Vec::new();
let r_variances = match variances {
Some(ref variances) => variances.regions.get_slice(space),
None => {
for _ in a_regions.iter() {
invariance.push(ty::Invariant);
}
invariance.as_slice()
}
};
let regions = try!(relate_region_params(self,
item_def_id,
r_variances,
a_regions,
b_regions));
substs.types.replace(space, tps);
substs.mut_regions().replace(space, regions);
}
return Ok(substs);
fn relate_region_params<C:Combine>(this: &C,
item_def_id: ast::DefId,
variances: &[ty::Variance],
a_rs: &[ty::Region],
b_rs: &[ty::Region])
-> cres<Vec<ty::Region>>
{
let tcx = this.infcx().tcx;
let num_region_params = variances.len();
debug!("relate_region_params(\
item_def_id={}, \
a_rs={}, \
b_rs={},
variances={})",
item_def_id.repr(tcx),
a_rs.repr(tcx),
b_rs.repr(tcx),
variances.repr(tcx));
assert_eq!(num_region_params, a_rs.len());
assert_eq!(num_region_params, b_rs.len());
let mut rs = vec!();
for i in range(0, num_region_params) {
let a_r = a_rs[i];
let b_r = b_rs[i];
let variance = variances[i];
let r = match variance {
ty::Invariant => this.equate().regions(a_r, b_r),
ty::Covariant => this.regions(a_r, b_r),
ty::Contravariant => this.contraregions(a_r, b_r),
ty::Bivariant => Ok(a_r),
};
rs.push(try!(r));
}
Ok(rs)
}
}
fn bare_fn_tys(&self, a: &ty::BareFnTy,
b: &ty::BareFnTy) -> cres<ty::BareFnTy> {
let fn_style = try!(self.fn_styles(a.fn_style, b.fn_style));
let abi = try!(self.abi(a.abi, b.abi));
let sig = try!(self.fn_sigs(&a.sig, &b.sig));
Ok(ty::BareFnTy {fn_style: fn_style,
abi: abi,
sig: sig})
}
fn closure_tys(&self, a: &ty::ClosureTy,
b: &ty::ClosureTy) -> cres<ty::ClosureTy> {
let store = match (a.store, b.store) {
(ty::RegionTraitStore(a_r, a_m),
ty::RegionTraitStore(b_r, b_m)) if a_m == b_m => {
let r = try!(self.contraregions(a_r, b_r));
ty::RegionTraitStore(r, a_m)
}
_ if a.store == b.store => {
a.store
}
_ => {
return Err(ty::terr_sigil_mismatch(expected_found(self, a.store, b.store)))
}
};
let fn_style = try!(self.fn_styles(a.fn_style, b.fn_style));
let onceness = try!(self.oncenesses(a.onceness, b.onceness));
let bounds = try!(self.existential_bounds(a.bounds, b.bounds));
let sig = try!(self.fn_sigs(&a.sig, &b.sig));
let abi = try!(self.abi(a.abi, b.abi));
Ok(ty::ClosureTy {
fn_style: fn_style,
onceness: onceness,
store: store,
bounds: bounds,
sig: sig,
abi: abi,
})
}
fn fn_sigs(&self, a: &ty::FnSig, b: &ty::FnSig) -> cres<ty::FnSig>;
fn args(&self, a: ty::t, b: ty::t) -> cres<ty::t> {
self.contratys(a, b).and_then(|t| Ok(t))
}
fn fn_styles(&self, a: FnStyle, b: FnStyle) -> cres<FnStyle>;
fn abi(&self, a: abi::Abi, b: abi::Abi) -> cres<abi::Abi> {
if a == b {
Ok(a)
} else {
Err(ty::terr_abi_mismatch(expected_found(self, a, b)))
}
}
fn oncenesses(&self, a: Onceness, b: Onceness) -> cres<Onceness>;
fn existential_bounds(&self,
a: ty::ExistentialBounds,
b: ty::ExistentialBounds)
-> cres<ty::ExistentialBounds>
{
let r = try!(self.contraregions(a.region_bound, b.region_bound));
let nb = try!(self.builtin_bounds(a.builtin_bounds, b.builtin_bounds));
Ok(ty::ExistentialBounds { region_bound: r,
builtin_bounds: nb })
}
fn builtin_bounds(&self,
a: ty::BuiltinBounds,
b: ty::BuiltinBounds)
-> cres<ty::BuiltinBounds>;
fn contraregions(&self, a: ty::Region, b: ty::Region)
-> cres<ty::Region>;
fn regions(&self, a: ty::Region, b: ty::Region) -> cres<ty::Region>;
fn trait_stores(&self,
vk: ty::terr_vstore_kind,
a: ty::TraitStore,
b: ty::TraitStore)
-> cres<ty::TraitStore> {
debug!("{}.trait_stores(a={}, b={})", self.tag(), a, b);
match (a, b) {
(ty::RegionTraitStore(a_r, a_m),
ty::RegionTraitStore(b_r, b_m)) if a_m == b_m => {
self.contraregions(a_r, b_r).and_then(|r| {
Ok(ty::RegionTraitStore(r, a_m))
})
}
_ if a == b => {
Ok(a)
}
_ => {
Err(ty::terr_trait_stores_differ(vk, expected_found(self, a, b)))
}
}
}
fn trait_refs(&self,
a: &ty::TraitRef,
b: &ty::TraitRef)
-> cres<ty::TraitRef> {
// Different traits cannot be related
// - NOTE in the future, expand out subtraits!
if a.def_id != b.def_id {
Err(ty::terr_traits(
expected_found(self, a.def_id, b.def_id)))
} else {
let substs = try!(self.substs(a.def_id, &a.substs, &b.substs));
Ok(ty::TraitRef { def_id: a.def_id,
substs: substs })
}
}
}
#[deriving(Clone)]
pub struct CombineFields<'a> {
pub infcx: &'a InferCtxt<'a>,
pub a_is_expected: bool,
pub trace: TypeTrace,
}
pub fn expected_found<C:Combine,T>(
this: &C, a: T, b: T) -> ty::expected_found<T> {
if this.a_is_expected() {
ty::expected_found {expected: a, found: b}
} else {
ty::expected_found {expected: b, found: a}
}
}
pub fn super_fn_sigs<C:Combine>(this: &C, a: &ty::FnSig, b: &ty::FnSig) -> cres<ty::FnSig> {
fn argvecs<C:Combine>(this: &C, a_args: &[ty::t], b_args: &[ty::t]) -> cres<Vec<ty::t> > {
if a_args.len() == b_args.len() {
result::collect(a_args.iter().zip(b_args.iter())
.map(|(a, b)| this.args(*a, *b)))
} else {
Err(ty::terr_arg_count)
}
}
if a.variadic != b.variadic {
return Err(ty::terr_variadic_mismatch(expected_found(this, a.variadic, b.variadic)));
}
let inputs = try!(argvecs(this,
a.inputs.as_slice(),
b.inputs.as_slice()));
let output = try!(this.tys(a.output, b.output));
Ok(FnSig {binder_id: a.binder_id,
inputs: inputs,
output: output,
variadic: a.variadic})
}
pub fn super_tys<C:Combine>(this: &C, a: ty::t, b: ty::t) -> cres<ty::t> {
// This is a horrible hack - historically, [T] was not treated as a type,
// so, for example, &T and &[U] should not unify. In fact the only thing
// &[U] should unify with is &[T]. We preserve that behaviour with this
// check.
fn check_ptr_to_unsized<C:Combine>(this: &C,
a: ty::t,
b: ty::t,
a_inner: ty::t,
b_inner: ty::t,
result: ty::t) -> cres<ty::t> {
match (&ty::get(a_inner).sty, &ty::get(b_inner).sty) {
(&ty::ty_vec(_, None), &ty::ty_vec(_, None)) |
(&ty::ty_str, &ty::ty_str) |
(&ty::ty_trait(..), &ty::ty_trait(..)) => Ok(result),
(&ty::ty_vec(_, None), _) | (_, &ty::ty_vec(_, None)) |
(&ty::ty_str, _) | (_, &ty::ty_str) |
(&ty::ty_trait(..), _) | (_, &ty::ty_trait(..))
=> Err(ty::terr_sorts(expected_found(this, a, b))),
_ => Ok(result),
}
}
let tcx = this.infcx().tcx;
let a_sty = &ty::get(a).sty;
let b_sty = &ty::get(b).sty;
debug!("super_tys: a_sty={:?} b_sty={:?}", a_sty, b_sty);
return match (a_sty, b_sty) {
// The "subtype" ought to be handling cases involving bot or var:
(&ty::ty_bot, _) |
(_, &ty::ty_bot) |
(&ty::ty_infer(TyVar(_)), _) |
(_, &ty::ty_infer(TyVar(_))) => {
tcx.sess.bug(
format!("{}: bot and var types should have been handled ({},{})",
this.tag(),
a.repr(this.infcx().tcx),
b.repr(this.infcx().tcx)).as_slice());
}
// Relate integral variables to other types
(&ty::ty_infer(IntVar(a_id)), &ty::ty_infer(IntVar(b_id))) => {
try!(this.infcx().simple_vars(this.a_is_expected(),
a_id, b_id));
Ok(a)
}
(&ty::ty_infer(IntVar(v_id)), &ty::ty_int(v)) => {
unify_integral_variable(this, this.a_is_expected(),
v_id, IntType(v))
}
(&ty::ty_int(v), &ty::ty_infer(IntVar(v_id))) => {
unify_integral_variable(this, !this.a_is_expected(),
v_id, IntType(v))
}
(&ty::ty_infer(IntVar(v_id)), &ty::ty_uint(v)) => {
unify_integral_variable(this, this.a_is_expected(),
v_id, UintType(v))
}
(&ty::ty_uint(v), &ty::ty_infer(IntVar(v_id))) => {
unify_integral_variable(this, !this.a_is_expected(),
v_id, UintType(v))
}
// Relate floating-point variables to other types
(&ty::ty_infer(FloatVar(a_id)), &ty::ty_infer(FloatVar(b_id))) => {
try!(this.infcx().simple_vars(this.a_is_expected(), a_id, b_id));
Ok(a)
}
(&ty::ty_infer(FloatVar(v_id)), &ty::ty_float(v)) => {
unify_float_variable(this, this.a_is_expected(), v_id, v)
}
(&ty::ty_float(v), &ty::ty_infer(FloatVar(v_id))) => {
unify_float_variable(this, !this.a_is_expected(), v_id, v)
}
(&ty::ty_char, _) |
(&ty::ty_nil, _) |
(&ty::ty_bool, _) |
(&ty::ty_int(_), _) |
(&ty::ty_uint(_), _) |
(&ty::ty_float(_), _) |
(&ty::ty_err, _) => {
if ty::get(a).sty == ty::get(b).sty {
Ok(a)
} else {
Err(ty::terr_sorts(expected_found(this, a, b)))
}
}
(&ty::ty_param(ref a_p), &ty::ty_param(ref b_p)) if
a_p.idx == b_p.idx && a_p.space == b_p.space => {
Ok(a)
}
(&ty::ty_enum(a_id, ref a_substs),
&ty::ty_enum(b_id, ref b_substs))
if a_id == b_id => {
let substs = try!(this.substs(a_id,
a_substs,
b_substs));
Ok(ty::mk_enum(tcx, a_id, substs))
}
(&ty::ty_trait(ref a_),
&ty::ty_trait(ref b_))
if a_.def_id == b_.def_id => {
debug!("Trying to match traits {:?} and {:?}", a, b);
let substs = try!(this.substs(a_.def_id, &a_.substs, &b_.substs));
let bounds = try!(this.existential_bounds(a_.bounds, b_.bounds));
Ok(ty::mk_trait(tcx,
a_.def_id,
substs.clone(),
bounds))
}
(&ty::ty_struct(a_id, ref a_substs), &ty::ty_struct(b_id, ref b_substs))
if a_id == b_id => {
let substs = try!(this.substs(a_id, a_substs, b_substs));
Ok(ty::mk_struct(tcx, a_id, substs))
}
(&ty::ty_unboxed_closure(a_id, a_region),
&ty::ty_unboxed_closure(b_id, b_region))
if a_id == b_id => {
// All ty_unboxed_closure types with the same id represent
// the (anonymous) type of the same closure expression. So
// all of their regions should be equated.
let region = try!(this.equate().regions(a_region, b_region));
Ok(ty::mk_unboxed_closure(tcx, a_id, region))
}
(&ty::ty_box(a_inner), &ty::ty_box(b_inner)) => {
this.tys(a_inner, b_inner).and_then(|typ| Ok(ty::mk_box(tcx, typ)))
}
(&ty::ty_uniq(a_inner), &ty::ty_uniq(b_inner)) => {
let typ = try!(this.tys(a_inner, b_inner));
check_ptr_to_unsized(this, a, b, a_inner, b_inner, ty::mk_uniq(tcx, typ))
}
(&ty::ty_ptr(ref a_mt), &ty::ty_ptr(ref b_mt)) => {
let mt = try!(this.mts(a_mt, b_mt));
check_ptr_to_unsized(this, a, b, a_mt.ty, b_mt.ty, ty::mk_ptr(tcx, mt))
}
(&ty::ty_rptr(a_r, ref a_mt), &ty::ty_rptr(b_r, ref b_mt)) => {
let r = try!(this.contraregions(a_r, b_r));
// FIXME(14985) If we have mutable references to trait objects, we
// used to use covariant subtyping. I have preserved this behaviour,
// even though it is probably incorrect. So don't go down the usual
// path which would require invariance.
let mt = match (&ty::get(a_mt.ty).sty, &ty::get(b_mt.ty).sty) {
(&ty::ty_trait(..), &ty::ty_trait(..)) if a_mt.mutbl == b_mt.mutbl => {
let ty = try!(this.tys(a_mt.ty, b_mt.ty));
ty::mt { ty: ty, mutbl: a_mt.mutbl }
}
_ => try!(this.mts(a_mt, b_mt))
};
check_ptr_to_unsized(this, a, b, a_mt.ty, b_mt.ty, ty::mk_rptr(tcx, r, mt))
}
(&ty::ty_vec(a_t, sz_a), &ty::ty_vec(b_t, sz_b)) => {
this.tys(a_t, b_t).and_then(|t| {
if sz_a == sz_b {
Ok(ty::mk_vec(tcx, t, sz_a))
} else {
Err(ty::terr_sorts(expected_found(this, a, b)))
}
})
}
(&ty::ty_str, &ty::ty_str) => {
Ok(ty::mk_str(tcx))
}
(&ty::ty_tup(ref as_), &ty::ty_tup(ref bs)) => {
if as_.len() == bs.len() {
result::collect(as_.iter().zip(bs.iter())
.map(|(a, b)| this.tys(*a, *b)))
.and_then(|ts| Ok(ty::mk_tup(tcx, ts)) )
} else {
Err(ty::terr_tuple_size(
expected_found(this, as_.len(), bs.len())))
}
}
(&ty::ty_bare_fn(ref a_fty), &ty::ty_bare_fn(ref b_fty)) => {
this.bare_fn_tys(a_fty, b_fty).and_then(|fty| {
Ok(ty::mk_bare_fn(tcx, fty))
})
}
(&ty::ty_closure(ref a_fty), &ty::ty_closure(ref b_fty)) => {
this.closure_tys(&**a_fty, &**b_fty).and_then(|fty| {
Ok(ty::mk_closure(tcx, fty))
})
}
_ => Err(ty::terr_sorts(expected_found(this, a, b)))
};
fn unify_integral_variable<C:Combine>(
this: &C,
vid_is_expected: bool,
vid: ty::IntVid,
val: ty::IntVarValue) -> cres<ty::t>
{
try!(this.infcx().simple_var_t(vid_is_expected, vid, val));
match val {
IntType(v) => Ok(ty::mk_mach_int(v)),
UintType(v) => Ok(ty::mk_mach_uint(v))
}
}
fn unify_float_variable<C:Combine>(
this: &C,
vid_is_expected: bool,
vid: ty::FloatVid,
val: ast::FloatTy) -> cres<ty::t>
{
try!(this.infcx().simple_var_t(vid_is_expected, vid, val));
Ok(ty::mk_mach_float(val))
}
}
impl<'f> CombineFields<'f> {
pub fn switch_expected(&self) -> CombineFields<'f> {
CombineFields {
a_is_expected: !self.a_is_expected,
..(*self).clone()
}
}
fn equate(&self) -> Equate<'f> {
Equate((*self).clone())
}
fn sub(&self) -> Sub<'f> {
Sub((*self).clone())
}
pub fn instantiate(&self,
a_ty: ty::t,
dir: RelationDir,
b_vid: ty::TyVid)
-> cres<()>
{
let tcx = self.infcx.tcx;
let mut stack = Vec::new();
stack.push((a_ty, dir, b_vid));
loop {
// For each turn of the loop, we extract a tuple
//
// (a_ty, dir, b_vid)
//
// to relate. Here dir is either SubtypeOf or
// SupertypeOf. The idea is that we should ensure that
// the type `a_ty` is a subtype or supertype (respectively) of the
// type to which `b_vid` is bound.
//
// If `b_vid` has not yet been instantiated with a type
// (which is always true on the first iteration, but not
// necessarily true on later iterations), we will first
// instantiate `b_vid` with a *generalized* version of
// `a_ty`. Generalization introduces other inference
// variables wherever subtyping could occur (at time of
// this writing, this means replacing free regions with
// region variables).
let (a_ty, dir, b_vid) = match stack.pop() {
None => break,
Some(e) => e,
};
debug!("instantiate(a_ty={} dir={} b_vid={})",
a_ty.repr(tcx),
dir,
b_vid.repr(tcx));
// Check whether `vid` has been instantiated yet. If not,
// make a generalized form of `ty` and instantiate with
// that.
let b_ty = self.infcx.type_variables.borrow().probe(b_vid);
let b_ty = match b_ty {
Some(t) => t, // ...already instantiated.
None => { // ...not yet instantiated:
// Generalize type if necessary.
let generalized_ty = match dir {
EqTo => a_ty,
SupertypeOf | SubtypeOf => self.generalize(a_ty)
};
debug!("instantiate(a_ty={}, dir={}, \
b_vid={}, generalized_ty={})",
a_ty.repr(tcx), dir, b_vid.repr(tcx),
generalized_ty.repr(tcx));
self.infcx.type_variables
.borrow_mut()
.instantiate_and_push(
b_vid, generalized_ty, &mut stack);
generalized_ty
}
};
// The original triple was `(a_ty, dir, b_vid)` -- now we have
// resolved `b_vid` to `b_ty`, so apply `(a_ty, dir, b_ty)`:
//
// FIXME: This code is non-ideal because all these subtype
// relations wind up attributed to the same spans. We need
// to associate causes/spans with each of the relations in
// the stack to get this right.
match dir {
EqTo => {
try!(self.equate().tys(a_ty, b_ty));
}
SubtypeOf => {
try!(self.sub().tys(a_ty, b_ty));
}
SupertypeOf => {
try!(self.sub().contratys(a_ty, b_ty));
}
}
}
Ok(())
}
fn generalize(&self, t: ty::t) -> ty::t {
// FIXME: This is non-ideal because we don't give a very descriptive
// origin for this region variable.
let infcx = self.infcx;
let span = self.trace.origin.span();
t.fold_with(
&mut RegionFolder::regions(
self.infcx.tcx,
|_| infcx.next_region_var(MiscVariable(span))))
}
}