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
use std::cmp::Ordering;
use crate::infer::InferCtxt;
use rustc_middle::infer::canonical::Canonical;
use rustc_middle::infer::canonical::CanonicalTyVarKind;
use rustc_middle::infer::canonical::CanonicalVarInfo;
use rustc_middle::infer::canonical::CanonicalVarInfos;
use rustc_middle::infer::canonical::CanonicalVarKind;
use rustc_middle::ty::BoundRegionKind::BrAnon;
use rustc_middle::ty::BoundTyKind;
use rustc_middle::ty::TyCtxt;
use rustc_middle::ty::TypeVisitableExt;
use rustc_middle::ty::{self, Ty};
use rustc_middle::ty::{TypeFoldable, TypeFolder, TypeSuperFoldable};
#[derive(Debug, Clone, Copy)]
pub enum CanonicalizeMode {
Input,
Response {
max_input_universe: ty::UniverseIndex,
},
}
pub struct Canonicalizer<'a, 'tcx> {
infcx: &'a InferCtxt<'tcx>,
canonicalize_mode: CanonicalizeMode,
variables: &'a mut Vec<ty::GenericArg<'tcx>>,
primitive_var_infos: Vec<CanonicalVarInfo<'tcx>>,
binder_index: ty::DebruijnIndex,
}
impl<'a, 'tcx> Canonicalizer<'a, 'tcx> {
#[instrument(level = "debug", skip(infcx), ret)]
pub fn canonicalize<T: TypeFoldable<TyCtxt<'tcx>>>(
infcx: &'a InferCtxt<'tcx>,
canonicalize_mode: CanonicalizeMode,
variables: &'a mut Vec<ty::GenericArg<'tcx>>,
value: T,
) -> Canonical<'tcx, T> {
let mut canonicalizer = Canonicalizer {
infcx,
canonicalize_mode,
variables,
primitive_var_infos: Vec::new(),
binder_index: ty::INNERMOST,
};
let value = value.fold_with(&mut canonicalizer);
assert!(!value.needs_infer());
assert!(!value.has_placeholders());
let (max_universe, variables) = canonicalizer.finalize();
Canonical { max_universe, variables, value }
}
fn finalize(self) -> (ty::UniverseIndex, CanonicalVarInfos<'tcx>) {
let mut var_infos = self.primitive_var_infos;
match self.canonicalize_mode {
CanonicalizeMode::Input => {}
CanonicalizeMode::Response { max_input_universe } => {
for var in var_infos.iter_mut() {
let uv = var.universe();
let new_uv = ty::UniverseIndex::from(
uv.index().saturating_sub(max_input_universe.index()),
);
*var = var.with_updated_universe(new_uv);
}
let max_universe = var_infos
.iter()
.map(|info| info.universe())
.max()
.unwrap_or(ty::UniverseIndex::ROOT);
let var_infos = self.infcx.tcx.mk_canonical_var_infos(&var_infos);
return (max_universe, var_infos);
}
}
let mut curr_compressed_uv = ty::UniverseIndex::ROOT;
let mut existential_in_new_uv = false;
let mut next_orig_uv = Some(ty::UniverseIndex::ROOT);
while let Some(orig_uv) = next_orig_uv.take() {
let mut update_uv = |var: &mut CanonicalVarInfo<'tcx>, orig_uv, is_existential| {
let uv = var.universe();
match uv.cmp(&orig_uv) {
Ordering::Less => (), Ordering::Equal => {
if is_existential {
existential_in_new_uv = true;
} else if existential_in_new_uv {
curr_compressed_uv = curr_compressed_uv.next_universe();
existential_in_new_uv = false;
}
*var = var.with_updated_universe(curr_compressed_uv);
}
Ordering::Greater => {
if next_orig_uv.map_or(true, |curr_next_uv| uv.cannot_name(curr_next_uv)) {
next_orig_uv = Some(uv);
}
}
}
};
for is_existential in [false, true] {
for var in var_infos.iter_mut() {
if !var.is_region() {
if is_existential == var.is_existential() {
update_uv(var, orig_uv, is_existential)
}
}
}
}
}
for var in var_infos.iter_mut() {
if var.is_region() {
assert!(var.is_existential());
*var = var.with_updated_universe(curr_compressed_uv);
}
}
let var_infos = self.infcx.tcx.mk_canonical_var_infos(&var_infos);
(curr_compressed_uv, var_infos)
}
}
impl<'tcx> TypeFolder<TyCtxt<'tcx>> for Canonicalizer<'_, 'tcx> {
fn interner(&self) -> TyCtxt<'tcx> {
self.infcx.tcx
}
fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
where
T: TypeFoldable<TyCtxt<'tcx>>,
{
self.binder_index.shift_in(1);
let t = t.super_fold_with(self);
self.binder_index.shift_out(1);
t
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
let r = self.infcx.shallow_resolve(r);
let kind = match *r {
ty::ReLateBound(..) => return r,
ty::ReStatic => match self.canonicalize_mode {
CanonicalizeMode::Input => CanonicalVarKind::Region(ty::UniverseIndex::ROOT),
CanonicalizeMode::Response { .. } => return r,
},
ty::ReErased | ty::ReFree(_) | ty::ReEarlyBound(_) => match self.canonicalize_mode {
CanonicalizeMode::Input => CanonicalVarKind::Region(ty::UniverseIndex::ROOT),
CanonicalizeMode::Response { .. } => bug!("unexpected region in response: {r:?}"),
},
ty::RePlaceholder(placeholder) => match self.canonicalize_mode {
CanonicalizeMode::Input => CanonicalVarKind::Region(ty::UniverseIndex::ROOT),
CanonicalizeMode::Response { max_input_universe } => {
if max_input_universe.can_name(placeholder.universe) {
bug!("new placeholder in universe {max_input_universe:?}: {r:?}");
}
CanonicalVarKind::PlaceholderRegion(placeholder)
}
},
ty::ReVar(_) => match self.canonicalize_mode {
CanonicalizeMode::Input => CanonicalVarKind::Region(ty::UniverseIndex::ROOT),
CanonicalizeMode::Response { .. } => {
CanonicalVarKind::Region(self.infcx.universe_of_region(r))
}
},
ty::ReError(_) => return r,
};
let existing_bound_var = match self.canonicalize_mode {
CanonicalizeMode::Input => None,
CanonicalizeMode::Response { .. } => {
self.variables.iter().position(|&v| v == r.into()).map(ty::BoundVar::from)
}
};
let var = existing_bound_var.unwrap_or_else(|| {
let var = ty::BoundVar::from(self.variables.len());
self.variables.push(r.into());
self.primitive_var_infos.push(CanonicalVarInfo { kind });
var
});
let br = ty::BoundRegion { var, kind: BrAnon(var.as_u32(), None) };
self.interner().mk_re_late_bound(self.binder_index, br)
}
fn fold_ty(&mut self, mut t: Ty<'tcx>) -> Ty<'tcx> {
let kind = match *t.kind() {
ty::Infer(ty::TyVar(mut vid)) => {
let root_vid = self.infcx.root_var(vid);
if root_vid != vid {
t = self.infcx.tcx.mk_ty_var(root_vid);
vid = root_vid;
}
match self.infcx.probe_ty_var(vid) {
Ok(t) => return self.fold_ty(t),
Err(ui) => CanonicalVarKind::Ty(CanonicalTyVarKind::General(ui)),
}
}
ty::Infer(ty::IntVar(vid)) => {
let nt = self.infcx.opportunistic_resolve_int_var(vid);
if nt != t {
return self.fold_ty(nt);
} else {
CanonicalVarKind::Ty(CanonicalTyVarKind::Int)
}
}
ty::Infer(ty::FloatVar(vid)) => {
let nt = self.infcx.opportunistic_resolve_float_var(vid);
if nt != t {
return self.fold_ty(nt);
} else {
CanonicalVarKind::Ty(CanonicalTyVarKind::Int)
}
}
ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
bug!("fresh var during canonicalization: {t:?}")
}
ty::Placeholder(placeholder) => match self.canonicalize_mode {
CanonicalizeMode::Input => CanonicalVarKind::PlaceholderTy(ty::Placeholder {
universe: placeholder.universe,
name: BoundTyKind::Anon(self.variables.len() as u32),
}),
CanonicalizeMode::Response { .. } => CanonicalVarKind::PlaceholderTy(placeholder),
},
ty::Param(_) => match self.canonicalize_mode {
CanonicalizeMode::Input => CanonicalVarKind::PlaceholderTy(ty::Placeholder {
universe: ty::UniverseIndex::ROOT,
name: ty::BoundTyKind::Anon(self.variables.len() as u32),
}),
CanonicalizeMode::Response { .. } => bug!("param ty in response: {t:?}"),
},
ty::Bool
| ty::Char
| ty::Int(_)
| ty::Uint(_)
| ty::Float(_)
| ty::Adt(_, _)
| ty::Foreign(_)
| ty::Str
| ty::Array(_, _)
| ty::Slice(_)
| ty::RawPtr(_)
| ty::Ref(_, _, _)
| ty::FnDef(_, _)
| ty::FnPtr(_)
| ty::Dynamic(_, _, _)
| ty::Closure(_, _)
| ty::Generator(_, _, _)
| ty::GeneratorWitness(_)
| ty::GeneratorWitnessMIR(..)
| ty::Never
| ty::Tuple(_)
| ty::Alias(_, _)
| ty::Bound(_, _)
| ty::Error(_) => return t.super_fold_with(self),
};
let var = ty::BoundVar::from(
self.variables.iter().position(|&v| v == t.into()).unwrap_or_else(|| {
let var = self.variables.len();
self.variables.push(t.into());
self.primitive_var_infos.push(CanonicalVarInfo { kind });
var
}),
);
let bt = ty::BoundTy { var, kind: BoundTyKind::Anon(var.index() as u32) };
self.interner().mk_bound(self.binder_index, bt)
}
fn fold_const(&mut self, mut c: ty::Const<'tcx>) -> ty::Const<'tcx> {
let kind = match c.kind() {
ty::ConstKind::Infer(ty::InferConst::Var(mut vid)) => {
let root_vid = self.infcx.root_const_var(vid);
if root_vid != vid {
c = self.infcx.tcx.mk_const(ty::InferConst::Var(root_vid), c.ty());
vid = root_vid;
}
match self.infcx.probe_const_var(vid) {
Ok(c) => return self.fold_const(c),
Err(universe) => CanonicalVarKind::Const(universe, c.ty()),
}
}
ty::ConstKind::Infer(ty::InferConst::Fresh(_)) => {
bug!("fresh var during canonicalization: {c:?}")
}
ty::ConstKind::Placeholder(placeholder) => match self.canonicalize_mode {
CanonicalizeMode::Input => CanonicalVarKind::PlaceholderConst(
ty::Placeholder {
universe: placeholder.universe,
name: ty::BoundVar::from(self.variables.len()),
},
c.ty(),
),
CanonicalizeMode::Response { .. } => {
CanonicalVarKind::PlaceholderConst(placeholder, c.ty())
}
},
ty::ConstKind::Param(_) => match self.canonicalize_mode {
CanonicalizeMode::Input => CanonicalVarKind::PlaceholderConst(
ty::Placeholder {
universe: ty::UniverseIndex::ROOT,
name: ty::BoundVar::from(self.variables.len()),
},
c.ty(),
),
CanonicalizeMode::Response { .. } => bug!("param ty in response: {c:?}"),
},
ty::ConstKind::Bound(_, _)
| ty::ConstKind::Unevaluated(_)
| ty::ConstKind::Value(_)
| ty::ConstKind::Error(_)
| ty::ConstKind::Expr(_) => return c.super_fold_with(self),
};
let var = ty::BoundVar::from(
self.variables.iter().position(|&v| v == c.into()).unwrap_or_else(|| {
let var = self.variables.len();
self.variables.push(c.into());
self.primitive_var_infos.push(CanonicalVarInfo { kind });
var
}),
);
self.interner().mk_const(ty::ConstKind::Bound(self.binder_index, var), c.ty())
}
}