]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_traits/src/chalk/lowering.rs
New upstream version 1.49.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_traits / src / chalk / lowering.rs
1 //! Contains the logic to lower rustc types into Chalk types
2 //!
3 //! In many cases there is a 1:1 relationship between a rustc type and a Chalk type.
4 //! For example, a `SubstsRef` maps almost directly to a `Substitution`. In some
5 //! other cases, such as `Param`s, there is no Chalk type, so we have to handle
6 //! accordingly.
7 //!
8 //! ## `Ty` lowering
9 //! Much of the `Ty` lowering is 1:1 with Chalk. (Or will be eventually). A
10 //! helpful table for what types lower to what can be found in the
11 //! [Chalk book](http://rust-lang.github.io/chalk/book/types/rust_types.html).
12 //! The most notable difference lies with `Param`s. To convert from rustc to
13 //! Chalk, we eagerly and deeply convert `Param`s to placeholders (in goals) or
14 //! bound variables (for clause generation through functions in `db`).
15 //!
16 //! ## `Region` lowering
17 //! Regions are handled in rustc and Chalk is quite differently. In rustc, there
18 //! is a difference between "early bound" and "late bound" regions, where only
19 //! the late bound regions have a `DebruijnIndex`. Moreover, in Chalk all
20 //! regions (Lifetimes) have an associated index. In rustc, only `BrAnon`s have
21 //! an index, whereas `BrNamed` don't. In order to lower regions to Chalk, we
22 //! convert all regions into `BrAnon` late-bound regions.
23 //!
24 //! ## `Const` lowering
25 //! Chalk doesn't handle consts currently, so consts are currently lowered to
26 //! an empty tuple.
27 //!
28 //! ## Bound variable collection
29 //! Another difference between rustc and Chalk lies in the handling of binders.
30 //! Chalk requires that we store the bound parameter kinds, whereas rustc does
31 //! not. To lower anything wrapped in a `Binder`, we first deeply find any bound
32 //! variables from the current `Binder`.
33
34 use rustc_ast::ast;
35 use rustc_middle::traits::{ChalkEnvironmentAndGoal, ChalkRustInterner as RustInterner};
36 use rustc_middle::ty::fold::TypeFolder;
37 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
38 use rustc_middle::ty::{
39 self, Binder, BoundRegion, Region, RegionKind, Ty, TyCtxt, TypeFoldable, TypeVisitor,
40 };
41 use rustc_span::def_id::DefId;
42
43 use chalk_ir::{FnSig, ForeignDefId};
44 use rustc_hir::Unsafety;
45 use std::collections::btree_map::{BTreeMap, Entry};
46 use std::ops::ControlFlow;
47
48 /// Essentially an `Into` with a `&RustInterner` parameter
49 crate trait LowerInto<'tcx, T> {
50 /// Lower a rustc construct (e.g., `ty::TraitPredicate`) to a chalk type, consuming `self`.
51 fn lower_into(self, interner: &RustInterner<'tcx>) -> T;
52 }
53
54 impl<'tcx> LowerInto<'tcx, chalk_ir::Substitution<RustInterner<'tcx>>> for SubstsRef<'tcx> {
55 fn lower_into(
56 self,
57 interner: &RustInterner<'tcx>,
58 ) -> chalk_ir::Substitution<RustInterner<'tcx>> {
59 chalk_ir::Substitution::from_iter(interner, self.iter().map(|s| s.lower_into(interner)))
60 }
61 }
62
63 impl<'tcx> LowerInto<'tcx, SubstsRef<'tcx>> for &chalk_ir::Substitution<RustInterner<'tcx>> {
64 fn lower_into(self, interner: &RustInterner<'tcx>) -> SubstsRef<'tcx> {
65 interner.tcx.mk_substs(self.iter(interner).map(|subst| subst.lower_into(interner)))
66 }
67 }
68
69 impl<'tcx> LowerInto<'tcx, chalk_ir::AliasTy<RustInterner<'tcx>>> for ty::ProjectionTy<'tcx> {
70 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::AliasTy<RustInterner<'tcx>> {
71 chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy {
72 associated_ty_id: chalk_ir::AssocTypeId(self.item_def_id),
73 substitution: self.substs.lower_into(interner),
74 })
75 }
76 }
77
78 impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment<chalk_ir::Goal<RustInterner<'tcx>>>>
79 for ChalkEnvironmentAndGoal<'tcx>
80 {
81 fn lower_into(
82 self,
83 interner: &RustInterner<'tcx>,
84 ) -> chalk_ir::InEnvironment<chalk_ir::Goal<RustInterner<'tcx>>> {
85 let clauses = self.environment.into_iter().map(|predicate| {
86 let (predicate, binders, _named_regions) = collect_bound_vars(
87 interner,
88 interner.tcx,
89 &predicate.bound_atom_with_opt_escaping(interner.tcx),
90 );
91 let consequence = match predicate {
92 ty::PredicateAtom::TypeWellFormedFromEnv(ty) => {
93 chalk_ir::DomainGoal::FromEnv(chalk_ir::FromEnv::Ty(ty.lower_into(interner)))
94 }
95 ty::PredicateAtom::Trait(predicate, _) => chalk_ir::DomainGoal::FromEnv(
96 chalk_ir::FromEnv::Trait(predicate.trait_ref.lower_into(interner)),
97 ),
98 ty::PredicateAtom::RegionOutlives(predicate) => chalk_ir::DomainGoal::Holds(
99 chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives {
100 a: predicate.0.lower_into(interner),
101 b: predicate.1.lower_into(interner),
102 }),
103 ),
104 ty::PredicateAtom::TypeOutlives(predicate) => chalk_ir::DomainGoal::Holds(
105 chalk_ir::WhereClause::TypeOutlives(chalk_ir::TypeOutlives {
106 ty: predicate.0.lower_into(interner),
107 lifetime: predicate.1.lower_into(interner),
108 }),
109 ),
110 ty::PredicateAtom::Projection(predicate) => chalk_ir::DomainGoal::Holds(
111 chalk_ir::WhereClause::AliasEq(predicate.lower_into(interner)),
112 ),
113 ty::PredicateAtom::WellFormed(..)
114 | ty::PredicateAtom::ObjectSafe(..)
115 | ty::PredicateAtom::ClosureKind(..)
116 | ty::PredicateAtom::Subtype(..)
117 | ty::PredicateAtom::ConstEvaluatable(..)
118 | ty::PredicateAtom::ConstEquate(..) => bug!("unexpected predicate {}", predicate),
119 };
120 let value = chalk_ir::ProgramClauseImplication {
121 consequence,
122 conditions: chalk_ir::Goals::empty(interner),
123 priority: chalk_ir::ClausePriority::High,
124 constraints: chalk_ir::Constraints::empty(interner),
125 };
126 chalk_ir::ProgramClauseData(chalk_ir::Binders::new(binders, value)).intern(interner)
127 });
128
129 let goal: chalk_ir::GoalData<RustInterner<'tcx>> = self.goal.lower_into(&interner);
130 chalk_ir::InEnvironment {
131 environment: chalk_ir::Environment {
132 clauses: chalk_ir::ProgramClauses::from_iter(&interner, clauses),
133 },
134 goal: goal.intern(&interner),
135 }
136 }
137 }
138
139 impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData<RustInterner<'tcx>>> for ty::Predicate<'tcx> {
140 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData<RustInterner<'tcx>> {
141 let (predicate, binders, _named_regions) = collect_bound_vars(
142 interner,
143 interner.tcx,
144 &self.bound_atom_with_opt_escaping(interner.tcx),
145 );
146
147 let value = match predicate {
148 ty::PredicateAtom::Trait(predicate, _) => {
149 chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
150 chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner)),
151 ))
152 }
153 ty::PredicateAtom::RegionOutlives(predicate) => {
154 chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
155 chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives {
156 a: predicate.0.lower_into(interner),
157 b: predicate.1.lower_into(interner),
158 }),
159 ))
160 }
161 ty::PredicateAtom::TypeOutlives(predicate) => {
162 chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
163 chalk_ir::WhereClause::TypeOutlives(chalk_ir::TypeOutlives {
164 ty: predicate.0.lower_into(interner),
165 lifetime: predicate.1.lower_into(interner),
166 }),
167 ))
168 }
169 ty::PredicateAtom::Projection(predicate) => {
170 chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
171 chalk_ir::WhereClause::AliasEq(predicate.lower_into(interner)),
172 ))
173 }
174 ty::PredicateAtom::WellFormed(arg) => match arg.unpack() {
175 GenericArgKind::Type(ty) => match ty.kind() {
176 // FIXME(chalk): In Chalk, a placeholder is WellFormed if it
177 // `FromEnv`. However, when we "lower" Params, we don't update
178 // the environment.
179 ty::Placeholder(..) => {
180 chalk_ir::GoalData::All(chalk_ir::Goals::empty(interner))
181 }
182
183 _ => chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::WellFormed(
184 chalk_ir::WellFormed::Ty(ty.lower_into(interner)),
185 )),
186 },
187 // FIXME(chalk): handle well formed consts
188 GenericArgKind::Const(..) => {
189 chalk_ir::GoalData::All(chalk_ir::Goals::empty(interner))
190 }
191 GenericArgKind::Lifetime(lt) => bug!("unexpect well formed predicate: {:?}", lt),
192 },
193
194 ty::PredicateAtom::ObjectSafe(t) => chalk_ir::GoalData::DomainGoal(
195 chalk_ir::DomainGoal::ObjectSafe(chalk_ir::TraitId(t)),
196 ),
197
198 // FIXME(chalk): other predicates
199 //
200 // We can defer this, but ultimately we'll want to express
201 // some of these in terms of chalk operations.
202 ty::PredicateAtom::ClosureKind(..)
203 | ty::PredicateAtom::Subtype(..)
204 | ty::PredicateAtom::ConstEvaluatable(..)
205 | ty::PredicateAtom::ConstEquate(..) => {
206 chalk_ir::GoalData::All(chalk_ir::Goals::empty(interner))
207 }
208 ty::PredicateAtom::TypeWellFormedFromEnv(ty) => chalk_ir::GoalData::DomainGoal(
209 chalk_ir::DomainGoal::FromEnv(chalk_ir::FromEnv::Ty(ty.lower_into(interner))),
210 ),
211 };
212
213 chalk_ir::GoalData::Quantified(
214 chalk_ir::QuantifierKind::ForAll,
215 chalk_ir::Binders::new(binders, value.intern(interner)),
216 )
217 }
218 }
219
220 impl<'tcx> LowerInto<'tcx, chalk_ir::TraitRef<RustInterner<'tcx>>>
221 for rustc_middle::ty::TraitRef<'tcx>
222 {
223 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::TraitRef<RustInterner<'tcx>> {
224 chalk_ir::TraitRef {
225 trait_id: chalk_ir::TraitId(self.def_id),
226 substitution: self.substs.lower_into(interner),
227 }
228 }
229 }
230
231 impl<'tcx> LowerInto<'tcx, chalk_ir::AliasEq<RustInterner<'tcx>>>
232 for rustc_middle::ty::ProjectionPredicate<'tcx>
233 {
234 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::AliasEq<RustInterner<'tcx>> {
235 chalk_ir::AliasEq {
236 ty: self.ty.lower_into(interner),
237 alias: self.projection_ty.lower_into(interner),
238 }
239 }
240 }
241
242 impl<'tcx> LowerInto<'tcx, chalk_ir::Ty<RustInterner<'tcx>>> for Ty<'tcx> {
243 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Ty<RustInterner<'tcx>> {
244 use rustc_ast as ast;
245
246 let int = |i| chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Int(i));
247 let uint = |i| chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(i));
248 let float = |f| chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Float(f));
249
250 match *self.kind() {
251 ty::Bool => chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Bool),
252 ty::Char => chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Char),
253 ty::Int(ty) => match ty {
254 ast::IntTy::Isize => int(chalk_ir::IntTy::Isize),
255 ast::IntTy::I8 => int(chalk_ir::IntTy::I8),
256 ast::IntTy::I16 => int(chalk_ir::IntTy::I16),
257 ast::IntTy::I32 => int(chalk_ir::IntTy::I32),
258 ast::IntTy::I64 => int(chalk_ir::IntTy::I64),
259 ast::IntTy::I128 => int(chalk_ir::IntTy::I128),
260 },
261 ty::Uint(ty) => match ty {
262 ast::UintTy::Usize => uint(chalk_ir::UintTy::Usize),
263 ast::UintTy::U8 => uint(chalk_ir::UintTy::U8),
264 ast::UintTy::U16 => uint(chalk_ir::UintTy::U16),
265 ast::UintTy::U32 => uint(chalk_ir::UintTy::U32),
266 ast::UintTy::U64 => uint(chalk_ir::UintTy::U64),
267 ast::UintTy::U128 => uint(chalk_ir::UintTy::U128),
268 },
269 ty::Float(ty) => match ty {
270 ast::FloatTy::F32 => float(chalk_ir::FloatTy::F32),
271 ast::FloatTy::F64 => float(chalk_ir::FloatTy::F64),
272 },
273 ty::Adt(def, substs) => {
274 chalk_ir::TyKind::Adt(chalk_ir::AdtId(def), substs.lower_into(interner))
275 }
276 ty::Foreign(def_id) => chalk_ir::TyKind::Foreign(ForeignDefId(def_id)),
277 ty::Str => chalk_ir::TyKind::Str,
278 ty::Array(ty, len) => {
279 chalk_ir::TyKind::Array(ty.lower_into(interner), len.lower_into(interner))
280 }
281 ty::Slice(ty) => chalk_ir::TyKind::Slice(ty.lower_into(interner)),
282
283 ty::RawPtr(ptr) => {
284 chalk_ir::TyKind::Raw(ptr.mutbl.lower_into(interner), ptr.ty.lower_into(interner))
285 }
286 ty::Ref(region, ty, mutability) => chalk_ir::TyKind::Ref(
287 mutability.lower_into(interner),
288 region.lower_into(interner),
289 ty.lower_into(interner),
290 ),
291 ty::FnDef(def_id, substs) => {
292 chalk_ir::TyKind::FnDef(chalk_ir::FnDefId(def_id), substs.lower_into(interner))
293 }
294 ty::FnPtr(sig) => {
295 let (inputs_and_outputs, binders, _named_regions) =
296 collect_bound_vars(interner, interner.tcx, &sig.inputs_and_output());
297 chalk_ir::TyKind::Function(chalk_ir::FnPointer {
298 num_binders: binders.len(interner),
299 sig: sig.lower_into(interner),
300 substitution: chalk_ir::Substitution::from_iter(
301 interner,
302 inputs_and_outputs.iter().map(|ty| {
303 chalk_ir::GenericArgData::Ty(ty.lower_into(interner)).intern(interner)
304 }),
305 ),
306 })
307 }
308 ty::Dynamic(predicates, region) => chalk_ir::TyKind::Dyn(chalk_ir::DynTy {
309 bounds: predicates.lower_into(interner),
310 lifetime: region.lower_into(interner),
311 }),
312 ty::Closure(def_id, substs) => {
313 chalk_ir::TyKind::Closure(chalk_ir::ClosureId(def_id), substs.lower_into(interner))
314 }
315 ty::Generator(_def_id, _substs, _) => unimplemented!(),
316 ty::GeneratorWitness(_) => unimplemented!(),
317 ty::Never => chalk_ir::TyKind::Never,
318 ty::Tuple(substs) => chalk_ir::TyKind::Tuple(substs.len(), substs.lower_into(interner)),
319 ty::Projection(proj) => chalk_ir::TyKind::Alias(proj.lower_into(interner)),
320 ty::Opaque(def_id, substs) => {
321 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Opaque(chalk_ir::OpaqueTy {
322 opaque_ty_id: chalk_ir::OpaqueTyId(def_id),
323 substitution: substs.lower_into(interner),
324 }))
325 }
326 // This should have been done eagerly prior to this, and all Params
327 // should have been substituted to placeholders
328 ty::Param(_) => panic!("Lowering Param when not expected."),
329 ty::Bound(db, bound) => chalk_ir::TyKind::BoundVar(chalk_ir::BoundVar::new(
330 chalk_ir::DebruijnIndex::new(db.as_u32()),
331 bound.var.index(),
332 )),
333 ty::Placeholder(_placeholder) => {
334 chalk_ir::TyKind::Placeholder(chalk_ir::PlaceholderIndex {
335 ui: chalk_ir::UniverseIndex { counter: _placeholder.universe.as_usize() },
336 idx: _placeholder.name.as_usize(),
337 })
338 }
339 ty::Infer(_infer) => unimplemented!(),
340 ty::Error(_) => chalk_ir::TyKind::Error,
341 }
342 .intern(interner)
343 }
344 }
345
346 impl<'tcx> LowerInto<'tcx, Ty<'tcx>> for &chalk_ir::Ty<RustInterner<'tcx>> {
347 fn lower_into(self, interner: &RustInterner<'tcx>) -> Ty<'tcx> {
348 use chalk_ir::TyKind;
349
350 let kind = match self.kind(interner) {
351 TyKind::Adt(struct_id, substitution) => {
352 ty::Adt(struct_id.0, substitution.lower_into(interner))
353 }
354 TyKind::Scalar(scalar) => match scalar {
355 chalk_ir::Scalar::Bool => ty::Bool,
356 chalk_ir::Scalar::Char => ty::Char,
357 chalk_ir::Scalar::Int(int_ty) => match int_ty {
358 chalk_ir::IntTy::Isize => ty::Int(ast::IntTy::Isize),
359 chalk_ir::IntTy::I8 => ty::Int(ast::IntTy::I8),
360 chalk_ir::IntTy::I16 => ty::Int(ast::IntTy::I16),
361 chalk_ir::IntTy::I32 => ty::Int(ast::IntTy::I32),
362 chalk_ir::IntTy::I64 => ty::Int(ast::IntTy::I64),
363 chalk_ir::IntTy::I128 => ty::Int(ast::IntTy::I128),
364 },
365 chalk_ir::Scalar::Uint(int_ty) => match int_ty {
366 chalk_ir::UintTy::Usize => ty::Uint(ast::UintTy::Usize),
367 chalk_ir::UintTy::U8 => ty::Uint(ast::UintTy::U8),
368 chalk_ir::UintTy::U16 => ty::Uint(ast::UintTy::U16),
369 chalk_ir::UintTy::U32 => ty::Uint(ast::UintTy::U32),
370 chalk_ir::UintTy::U64 => ty::Uint(ast::UintTy::U64),
371 chalk_ir::UintTy::U128 => ty::Uint(ast::UintTy::U128),
372 },
373 chalk_ir::Scalar::Float(float_ty) => match float_ty {
374 chalk_ir::FloatTy::F32 => ty::Float(ast::FloatTy::F32),
375 chalk_ir::FloatTy::F64 => ty::Float(ast::FloatTy::F64),
376 },
377 },
378 TyKind::Array(ty, c) => {
379 let ty = ty.lower_into(interner);
380 let c = c.lower_into(interner);
381 ty::Array(ty, interner.tcx.mk_const(c))
382 }
383 TyKind::FnDef(id, substitution) => ty::FnDef(id.0, substitution.lower_into(interner)),
384 TyKind::Closure(closure, substitution) => {
385 ty::Closure(closure.0, substitution.lower_into(interner))
386 }
387 TyKind::Generator(..) => unimplemented!(),
388 TyKind::GeneratorWitness(..) => unimplemented!(),
389 TyKind::Never => ty::Never,
390 TyKind::Tuple(_len, substitution) => ty::Tuple(substitution.lower_into(interner)),
391 TyKind::Slice(ty) => ty::Slice(ty.lower_into(interner)),
392 TyKind::Raw(mutbl, ty) => ty::RawPtr(ty::TypeAndMut {
393 ty: ty.lower_into(interner),
394 mutbl: mutbl.lower_into(interner),
395 }),
396 TyKind::Ref(mutbl, lifetime, ty) => ty::Ref(
397 lifetime.lower_into(interner),
398 ty.lower_into(interner),
399 mutbl.lower_into(interner),
400 ),
401 TyKind::Str => ty::Str,
402 TyKind::OpaqueType(opaque_ty, substitution) => {
403 ty::Opaque(opaque_ty.0, substitution.lower_into(interner))
404 }
405 TyKind::AssociatedType(assoc_ty, substitution) => ty::Projection(ty::ProjectionTy {
406 substs: substitution.lower_into(interner),
407 item_def_id: assoc_ty.0,
408 }),
409 TyKind::Foreign(def_id) => ty::Foreign(def_id.0),
410 TyKind::Error => return interner.tcx.ty_error(),
411 TyKind::Placeholder(placeholder) => ty::Placeholder(ty::Placeholder {
412 universe: ty::UniverseIndex::from_usize(placeholder.ui.counter),
413 name: ty::BoundVar::from_usize(placeholder.idx),
414 }),
415 TyKind::Alias(alias_ty) => match alias_ty {
416 chalk_ir::AliasTy::Projection(projection) => ty::Projection(ty::ProjectionTy {
417 item_def_id: projection.associated_ty_id.0,
418 substs: projection.substitution.lower_into(interner),
419 }),
420 chalk_ir::AliasTy::Opaque(opaque) => {
421 ty::Opaque(opaque.opaque_ty_id.0, opaque.substitution.lower_into(interner))
422 }
423 },
424 TyKind::Function(_quantified_ty) => unimplemented!(),
425 TyKind::BoundVar(_bound) => ty::Bound(
426 ty::DebruijnIndex::from_usize(_bound.debruijn.depth() as usize),
427 ty::BoundTy {
428 var: ty::BoundVar::from_usize(_bound.index),
429 kind: ty::BoundTyKind::Anon,
430 },
431 ),
432 TyKind::InferenceVar(_, _) => unimplemented!(),
433 TyKind::Dyn(_) => unimplemented!(),
434 };
435 interner.tcx.mk_ty(kind)
436 }
437 }
438
439 impl<'tcx> LowerInto<'tcx, chalk_ir::Lifetime<RustInterner<'tcx>>> for Region<'tcx> {
440 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Lifetime<RustInterner<'tcx>> {
441 use rustc_middle::ty::RegionKind::*;
442
443 match self {
444 ReEarlyBound(_) => {
445 panic!("Should have already been substituted.");
446 }
447 ReLateBound(db, br) => match br {
448 ty::BoundRegion::BrAnon(var) => {
449 chalk_ir::LifetimeData::BoundVar(chalk_ir::BoundVar::new(
450 chalk_ir::DebruijnIndex::new(db.as_u32()),
451 *var as usize,
452 ))
453 .intern(interner)
454 }
455 ty::BoundRegion::BrNamed(_def_id, _name) => unimplemented!(),
456 ty::BrEnv => unimplemented!(),
457 },
458 ReFree(_) => unimplemented!(),
459 ReStatic => chalk_ir::LifetimeData::Static.intern(interner),
460 ReVar(_) => unimplemented!(),
461 RePlaceholder(placeholder_region) => {
462 chalk_ir::LifetimeData::Placeholder(chalk_ir::PlaceholderIndex {
463 ui: chalk_ir::UniverseIndex { counter: placeholder_region.universe.index() },
464 idx: 0,
465 })
466 .intern(interner)
467 }
468 ReEmpty(_) => unimplemented!(),
469 // FIXME(chalk): need to handle ReErased
470 ReErased => unimplemented!(),
471 }
472 }
473 }
474
475 impl<'tcx> LowerInto<'tcx, Region<'tcx>> for &chalk_ir::Lifetime<RustInterner<'tcx>> {
476 fn lower_into(self, interner: &RustInterner<'tcx>) -> Region<'tcx> {
477 let kind = match self.data(interner) {
478 chalk_ir::LifetimeData::BoundVar(var) => ty::RegionKind::ReLateBound(
479 ty::DebruijnIndex::from_u32(var.debruijn.depth()),
480 ty::BoundRegion::BrAnon(var.index as u32),
481 ),
482 chalk_ir::LifetimeData::InferenceVar(_var) => unimplemented!(),
483 chalk_ir::LifetimeData::Placeholder(p) => {
484 ty::RegionKind::RePlaceholder(ty::Placeholder {
485 universe: ty::UniverseIndex::from_usize(p.ui.counter),
486 name: ty::BoundRegion::BrAnon(p.idx as u32),
487 })
488 }
489 chalk_ir::LifetimeData::Static => ty::RegionKind::ReStatic,
490 chalk_ir::LifetimeData::Phantom(_, _) => unimplemented!(),
491 };
492 interner.tcx.mk_region(kind)
493 }
494 }
495
496 impl<'tcx> LowerInto<'tcx, chalk_ir::Const<RustInterner<'tcx>>> for ty::Const<'tcx> {
497 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Const<RustInterner<'tcx>> {
498 let ty = self.ty.lower_into(interner);
499 let value = match self.val {
500 ty::ConstKind::Value(val) => {
501 chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: val })
502 }
503 ty::ConstKind::Bound(db, bound) => chalk_ir::ConstValue::BoundVar(
504 chalk_ir::BoundVar::new(chalk_ir::DebruijnIndex::new(db.as_u32()), bound.index()),
505 ),
506 _ => unimplemented!("Const not implemented. {:?}", self),
507 };
508 chalk_ir::ConstData { ty, value }.intern(interner)
509 }
510 }
511
512 impl<'tcx> LowerInto<'tcx, ty::Const<'tcx>> for &chalk_ir::Const<RustInterner<'tcx>> {
513 fn lower_into(self, interner: &RustInterner<'tcx>) -> ty::Const<'tcx> {
514 let data = self.data(interner);
515 let ty = data.ty.lower_into(interner);
516 let val = match data.value {
517 chalk_ir::ConstValue::BoundVar(var) => ty::ConstKind::Bound(
518 ty::DebruijnIndex::from_u32(var.debruijn.depth()),
519 ty::BoundVar::from_u32(var.index as u32),
520 ),
521 chalk_ir::ConstValue::InferenceVar(_var) => unimplemented!(),
522 chalk_ir::ConstValue::Placeholder(_p) => unimplemented!(),
523 chalk_ir::ConstValue::Concrete(c) => ty::ConstKind::Value(c.interned),
524 };
525 ty::Const { ty, val }
526 }
527 }
528
529 impl<'tcx> LowerInto<'tcx, chalk_ir::GenericArg<RustInterner<'tcx>>> for GenericArg<'tcx> {
530 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GenericArg<RustInterner<'tcx>> {
531 match self.unpack() {
532 ty::subst::GenericArgKind::Type(ty) => {
533 chalk_ir::GenericArgData::Ty(ty.lower_into(interner))
534 }
535 ty::subst::GenericArgKind::Lifetime(lifetime) => {
536 chalk_ir::GenericArgData::Lifetime(lifetime.lower_into(interner))
537 }
538 ty::subst::GenericArgKind::Const(c) => {
539 chalk_ir::GenericArgData::Const(c.lower_into(interner))
540 }
541 }
542 .intern(interner)
543 }
544 }
545
546 impl<'tcx> LowerInto<'tcx, ty::subst::GenericArg<'tcx>>
547 for &chalk_ir::GenericArg<RustInterner<'tcx>>
548 {
549 fn lower_into(self, interner: &RustInterner<'tcx>) -> ty::subst::GenericArg<'tcx> {
550 match self.data(interner) {
551 chalk_ir::GenericArgData::Ty(ty) => {
552 let t: Ty<'tcx> = ty.lower_into(interner);
553 t.into()
554 }
555 chalk_ir::GenericArgData::Lifetime(lifetime) => {
556 let r: Region<'tcx> = lifetime.lower_into(interner);
557 r.into()
558 }
559 chalk_ir::GenericArgData::Const(c) => {
560 let c: ty::Const<'tcx> = c.lower_into(interner);
561 interner.tcx.mk_const(c).into()
562 }
563 }
564 }
565 }
566
567 // We lower into an Option here since there are some predicates which Chalk
568 // doesn't have a representation for yet (as a `WhereClause`), but are so common
569 // that we just are accepting the unsoundness for now. The `Option` will
570 // eventually be removed.
571 impl<'tcx> LowerInto<'tcx, Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>>>
572 for ty::Predicate<'tcx>
573 {
574 fn lower_into(
575 self,
576 interner: &RustInterner<'tcx>,
577 ) -> Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>> {
578 let (predicate, binders, _named_regions) = collect_bound_vars(
579 interner,
580 interner.tcx,
581 &self.bound_atom_with_opt_escaping(interner.tcx),
582 );
583 let value = match predicate {
584 ty::PredicateAtom::Trait(predicate, _) => {
585 Some(chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner)))
586 }
587 ty::PredicateAtom::RegionOutlives(predicate) => {
588 Some(chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives {
589 a: predicate.0.lower_into(interner),
590 b: predicate.1.lower_into(interner),
591 }))
592 }
593 ty::PredicateAtom::TypeOutlives(predicate) => {
594 Some(chalk_ir::WhereClause::TypeOutlives(chalk_ir::TypeOutlives {
595 ty: predicate.0.lower_into(interner),
596 lifetime: predicate.1.lower_into(interner),
597 }))
598 }
599 ty::PredicateAtom::Projection(predicate) => {
600 Some(chalk_ir::WhereClause::AliasEq(predicate.lower_into(interner)))
601 }
602 ty::PredicateAtom::WellFormed(_ty) => None,
603
604 ty::PredicateAtom::ObjectSafe(..)
605 | ty::PredicateAtom::ClosureKind(..)
606 | ty::PredicateAtom::Subtype(..)
607 | ty::PredicateAtom::ConstEvaluatable(..)
608 | ty::PredicateAtom::ConstEquate(..)
609 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => {
610 bug!("unexpected predicate {}", &self)
611 }
612 };
613 value.map(|value| chalk_ir::Binders::new(binders, value))
614 }
615 }
616
617 impl<'tcx> LowerInto<'tcx, chalk_ir::Binders<chalk_ir::QuantifiedWhereClauses<RustInterner<'tcx>>>>
618 for Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>
619 {
620 fn lower_into(
621 self,
622 interner: &RustInterner<'tcx>,
623 ) -> chalk_ir::Binders<chalk_ir::QuantifiedWhereClauses<RustInterner<'tcx>>> {
624 // `Self` has one binder:
625 // Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>
626 // The return type has two:
627 // Binders<&[Binders<WhereClause<I>>]>
628 // This means that any variables that are escaping `self` need to be
629 // shifted in by one so that they are still escaping.
630 let shifted_predicates = ty::fold::shift_vars(interner.tcx, &self, 1);
631
632 let (predicates, binders, _named_regions) =
633 collect_bound_vars(interner, interner.tcx, &shifted_predicates);
634 let self_ty = interner.tcx.mk_ty(ty::Bound(
635 // This is going to be wrapped in a binder
636 ty::DebruijnIndex::from_usize(1),
637 ty::BoundTy { var: ty::BoundVar::from_usize(0), kind: ty::BoundTyKind::Anon },
638 ));
639 let where_clauses = predicates.into_iter().map(|predicate| match predicate {
640 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef { def_id, substs }) => {
641 chalk_ir::Binders::new(
642 binders.clone(),
643 chalk_ir::WhereClause::Implemented(chalk_ir::TraitRef {
644 trait_id: chalk_ir::TraitId(def_id),
645 substitution: interner
646 .tcx
647 .mk_substs_trait(self_ty, substs)
648 .lower_into(interner),
649 }),
650 )
651 }
652 ty::ExistentialPredicate::Projection(predicate) => chalk_ir::Binders::new(
653 binders.clone(),
654 chalk_ir::WhereClause::AliasEq(chalk_ir::AliasEq {
655 alias: chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy {
656 associated_ty_id: chalk_ir::AssocTypeId(predicate.item_def_id),
657 substitution: interner
658 .tcx
659 .mk_substs_trait(self_ty, predicate.substs)
660 .lower_into(interner),
661 }),
662 ty: predicate.ty.lower_into(interner),
663 }),
664 ),
665 ty::ExistentialPredicate::AutoTrait(def_id) => chalk_ir::Binders::new(
666 binders.clone(),
667 chalk_ir::WhereClause::Implemented(chalk_ir::TraitRef {
668 trait_id: chalk_ir::TraitId(def_id),
669 substitution: interner.tcx.mk_substs_trait(self_ty, &[]).lower_into(interner),
670 }),
671 ),
672 });
673
674 // Binder for the bound variable representing the concrete underlying type.
675 let existential_binder = chalk_ir::VariableKinds::from1(
676 interner,
677 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
678 );
679 let value = chalk_ir::QuantifiedWhereClauses::from_iter(interner, where_clauses);
680 chalk_ir::Binders::new(existential_binder, value)
681 }
682 }
683
684 impl<'tcx> LowerInto<'tcx, chalk_ir::FnSig<RustInterner<'tcx>>> for ty::Binder<ty::FnSig<'tcx>> {
685 fn lower_into(self, _interner: &RustInterner<'_>) -> FnSig<RustInterner<'tcx>> {
686 chalk_ir::FnSig {
687 abi: self.abi(),
688 safety: match self.unsafety() {
689 Unsafety::Normal => chalk_ir::Safety::Safe,
690 Unsafety::Unsafe => chalk_ir::Safety::Unsafe,
691 },
692 variadic: self.c_variadic(),
693 }
694 }
695 }
696
697 // We lower into an Option here since there are some predicates which Chalk
698 // doesn't have a representation for yet (as an `InlineBound`). The `Option` will
699 // eventually be removed.
700 impl<'tcx> LowerInto<'tcx, Option<chalk_solve::rust_ir::QuantifiedInlineBound<RustInterner<'tcx>>>>
701 for ty::Predicate<'tcx>
702 {
703 fn lower_into(
704 self,
705 interner: &RustInterner<'tcx>,
706 ) -> Option<chalk_solve::rust_ir::QuantifiedInlineBound<RustInterner<'tcx>>> {
707 let (predicate, binders, _named_regions) = collect_bound_vars(
708 interner,
709 interner.tcx,
710 &self.bound_atom_with_opt_escaping(interner.tcx),
711 );
712 match predicate {
713 ty::PredicateAtom::Trait(predicate, _) => Some(chalk_ir::Binders::new(
714 binders,
715 chalk_solve::rust_ir::InlineBound::TraitBound(
716 predicate.trait_ref.lower_into(interner),
717 ),
718 )),
719 ty::PredicateAtom::Projection(predicate) => Some(chalk_ir::Binders::new(
720 binders,
721 chalk_solve::rust_ir::InlineBound::AliasEqBound(predicate.lower_into(interner)),
722 )),
723 ty::PredicateAtom::TypeOutlives(_predicate) => None,
724 ty::PredicateAtom::WellFormed(_ty) => None,
725
726 ty::PredicateAtom::RegionOutlives(..)
727 | ty::PredicateAtom::ObjectSafe(..)
728 | ty::PredicateAtom::ClosureKind(..)
729 | ty::PredicateAtom::Subtype(..)
730 | ty::PredicateAtom::ConstEvaluatable(..)
731 | ty::PredicateAtom::ConstEquate(..)
732 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => {
733 bug!("unexpected predicate {}", &self)
734 }
735 }
736 }
737 }
738
739 impl<'tcx> LowerInto<'tcx, chalk_solve::rust_ir::TraitBound<RustInterner<'tcx>>>
740 for ty::TraitRef<'tcx>
741 {
742 fn lower_into(
743 self,
744 interner: &RustInterner<'tcx>,
745 ) -> chalk_solve::rust_ir::TraitBound<RustInterner<'tcx>> {
746 chalk_solve::rust_ir::TraitBound {
747 trait_id: chalk_ir::TraitId(self.def_id),
748 args_no_self: self.substs[1..].iter().map(|arg| arg.lower_into(interner)).collect(),
749 }
750 }
751 }
752
753 impl<'tcx> LowerInto<'tcx, chalk_ir::Mutability> for ast::Mutability {
754 fn lower_into(self, _interner: &RustInterner<'tcx>) -> chalk_ir::Mutability {
755 match self {
756 rustc_ast::Mutability::Mut => chalk_ir::Mutability::Mut,
757 rustc_ast::Mutability::Not => chalk_ir::Mutability::Not,
758 }
759 }
760 }
761
762 impl<'tcx> LowerInto<'tcx, ast::Mutability> for chalk_ir::Mutability {
763 fn lower_into(self, _interner: &RustInterner<'tcx>) -> ast::Mutability {
764 match self {
765 chalk_ir::Mutability::Mut => ast::Mutability::Mut,
766 chalk_ir::Mutability::Not => ast::Mutability::Not,
767 }
768 }
769 }
770
771 impl<'tcx> LowerInto<'tcx, chalk_solve::rust_ir::Polarity> for ty::ImplPolarity {
772 fn lower_into(self, _interner: &RustInterner<'tcx>) -> chalk_solve::rust_ir::Polarity {
773 match self {
774 ty::ImplPolarity::Positive => chalk_solve::rust_ir::Polarity::Positive,
775 ty::ImplPolarity::Negative => chalk_solve::rust_ir::Polarity::Negative,
776 // FIXME(chalk) reservation impls
777 ty::ImplPolarity::Reservation => chalk_solve::rust_ir::Polarity::Negative,
778 }
779 }
780 }
781
782 impl<'tcx> LowerInto<'tcx, chalk_solve::rust_ir::AliasEqBound<RustInterner<'tcx>>>
783 for ty::ProjectionPredicate<'tcx>
784 {
785 fn lower_into(
786 self,
787 interner: &RustInterner<'tcx>,
788 ) -> chalk_solve::rust_ir::AliasEqBound<RustInterner<'tcx>> {
789 let trait_ref = self.projection_ty.trait_ref(interner.tcx);
790 chalk_solve::rust_ir::AliasEqBound {
791 trait_bound: trait_ref.lower_into(interner),
792 associated_ty_id: chalk_ir::AssocTypeId(self.projection_ty.item_def_id),
793 parameters: self.projection_ty.substs[trait_ref.substs.len()..]
794 .iter()
795 .map(|arg| arg.lower_into(interner))
796 .collect(),
797 value: self.ty.lower_into(interner),
798 }
799 }
800 }
801
802 /// To collect bound vars, we have to do two passes. In the first pass, we
803 /// collect all `BoundRegion`s and `ty::Bound`s. In the second pass, we then
804 /// replace `BrNamed` into `BrAnon`. The two separate passes are important,
805 /// since we can only replace `BrNamed` with `BrAnon`s with indices *after* all
806 /// "real" `BrAnon`s.
807 ///
808 /// It's important to note that because of prior substitution, we may have
809 /// late-bound regions, even outside of fn contexts, since this is the best way
810 /// to prep types for chalk lowering.
811 crate fn collect_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>>(
812 interner: &RustInterner<'tcx>,
813 tcx: TyCtxt<'tcx>,
814 ty: &'a Binder<T>,
815 ) -> (T, chalk_ir::VariableKinds<RustInterner<'tcx>>, BTreeMap<DefId, u32>) {
816 let mut bound_vars_collector = BoundVarsCollector::new();
817 ty.as_ref().skip_binder().visit_with(&mut bound_vars_collector);
818 let mut parameters = bound_vars_collector.parameters;
819 let named_parameters: BTreeMap<DefId, u32> = bound_vars_collector
820 .named_parameters
821 .into_iter()
822 .enumerate()
823 .map(|(i, def_id)| (def_id, (i + parameters.len()) as u32))
824 .collect();
825
826 let mut bound_var_substitutor = NamedBoundVarSubstitutor::new(tcx, &named_parameters);
827 let new_ty = ty.as_ref().skip_binder().fold_with(&mut bound_var_substitutor);
828
829 for var in named_parameters.values() {
830 parameters.insert(*var, chalk_ir::VariableKind::Lifetime);
831 }
832
833 (0..parameters.len()).for_each(|i| {
834 parameters
835 .get(&(i as u32))
836 .or_else(|| bug!("Skipped bound var index: ty={:?}, parameters={:?}", ty, parameters));
837 });
838
839 let binders =
840 chalk_ir::VariableKinds::from_iter(interner, parameters.into_iter().map(|(_, v)| v));
841
842 (new_ty, binders, named_parameters)
843 }
844
845 crate struct BoundVarsCollector<'tcx> {
846 binder_index: ty::DebruijnIndex,
847 crate parameters: BTreeMap<u32, chalk_ir::VariableKind<RustInterner<'tcx>>>,
848 crate named_parameters: Vec<DefId>,
849 }
850
851 impl<'tcx> BoundVarsCollector<'tcx> {
852 crate fn new() -> Self {
853 BoundVarsCollector {
854 binder_index: ty::INNERMOST,
855 parameters: BTreeMap::new(),
856 named_parameters: vec![],
857 }
858 }
859 }
860
861 impl<'tcx> TypeVisitor<'tcx> for BoundVarsCollector<'tcx> {
862 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> ControlFlow<()> {
863 self.binder_index.shift_in(1);
864 let result = t.super_visit_with(self);
865 self.binder_index.shift_out(1);
866 result
867 }
868
869 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<()> {
870 match *t.kind() {
871 ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
872 match self.parameters.entry(bound_ty.var.as_u32()) {
873 Entry::Vacant(entry) => {
874 entry.insert(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General));
875 }
876 Entry::Occupied(entry) => match entry.get() {
877 chalk_ir::VariableKind::Ty(_) => {}
878 _ => panic!(),
879 },
880 }
881 }
882
883 _ => (),
884 };
885
886 t.super_visit_with(self)
887 }
888
889 fn visit_region(&mut self, r: Region<'tcx>) -> ControlFlow<()> {
890 match r {
891 ty::ReLateBound(index, br) if *index == self.binder_index => match br {
892 ty::BoundRegion::BrNamed(def_id, _name) => {
893 if self.named_parameters.iter().find(|d| *d == def_id).is_none() {
894 self.named_parameters.push(*def_id);
895 }
896 }
897
898 ty::BoundRegion::BrAnon(var) => match self.parameters.entry(*var) {
899 Entry::Vacant(entry) => {
900 entry.insert(chalk_ir::VariableKind::Lifetime);
901 }
902 Entry::Occupied(entry) => match entry.get() {
903 chalk_ir::VariableKind::Lifetime => {}
904 _ => panic!(),
905 },
906 },
907
908 ty::BrEnv => unimplemented!(),
909 },
910
911 ty::ReEarlyBound(_re) => {
912 // FIXME(chalk): jackh726 - I think we should always have already
913 // substituted away `ReEarlyBound`s for `ReLateBound`s, but need to confirm.
914 unimplemented!();
915 }
916
917 _ => (),
918 };
919
920 r.super_visit_with(self)
921 }
922 }
923
924 /// This is used to replace `BoundRegion::BrNamed` with `BoundRegion::BrAnon`.
925 /// Note: we assume that we will always have room for more bound vars. (i.e. we
926 /// won't ever hit the `u32` limit in `BrAnon`s).
927 struct NamedBoundVarSubstitutor<'a, 'tcx> {
928 tcx: TyCtxt<'tcx>,
929 binder_index: ty::DebruijnIndex,
930 named_parameters: &'a BTreeMap<DefId, u32>,
931 }
932
933 impl<'a, 'tcx> NamedBoundVarSubstitutor<'a, 'tcx> {
934 fn new(tcx: TyCtxt<'tcx>, named_parameters: &'a BTreeMap<DefId, u32>) -> Self {
935 NamedBoundVarSubstitutor { tcx, binder_index: ty::INNERMOST, named_parameters }
936 }
937 }
938
939 impl<'a, 'tcx> TypeFolder<'tcx> for NamedBoundVarSubstitutor<'a, 'tcx> {
940 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
941 self.tcx
942 }
943
944 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> Binder<T> {
945 self.binder_index.shift_in(1);
946 let result = t.super_fold_with(self);
947 self.binder_index.shift_out(1);
948 result
949 }
950
951 fn fold_region(&mut self, r: Region<'tcx>) -> Region<'tcx> {
952 match r {
953 ty::ReLateBound(index, br) if *index == self.binder_index => match br {
954 ty::BoundRegion::BrNamed(def_id, _name) => {
955 match self.named_parameters.get(def_id) {
956 Some(idx) => {
957 return self.tcx.mk_region(RegionKind::ReLateBound(
958 *index,
959 BoundRegion::BrAnon(*idx),
960 ));
961 }
962 None => panic!("Missing `BrNamed`."),
963 }
964 }
965 ty::BrEnv => unimplemented!(),
966 ty::BoundRegion::BrAnon(_) => {}
967 },
968 _ => (),
969 };
970
971 r.super_fold_with(self)
972 }
973 }
974
975 /// Used to substitute `Param`s with placeholders. We do this since Chalk
976 /// have a notion of `Param`s.
977 crate struct ParamsSubstitutor<'tcx> {
978 tcx: TyCtxt<'tcx>,
979 binder_index: ty::DebruijnIndex,
980 list: Vec<rustc_middle::ty::ParamTy>,
981 next_ty_placeholder: usize,
982 crate params: rustc_data_structures::fx::FxHashMap<usize, rustc_middle::ty::ParamTy>,
983 crate named_regions: BTreeMap<DefId, u32>,
984 }
985
986 impl<'tcx> ParamsSubstitutor<'tcx> {
987 crate fn new(tcx: TyCtxt<'tcx>, next_ty_placeholder: usize) -> Self {
988 ParamsSubstitutor {
989 tcx,
990 binder_index: ty::INNERMOST,
991 list: vec![],
992 next_ty_placeholder,
993 params: rustc_data_structures::fx::FxHashMap::default(),
994 named_regions: BTreeMap::default(),
995 }
996 }
997 }
998
999 impl<'tcx> TypeFolder<'tcx> for ParamsSubstitutor<'tcx> {
1000 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1001 self.tcx
1002 }
1003
1004 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> Binder<T> {
1005 self.binder_index.shift_in(1);
1006 let result = t.super_fold_with(self);
1007 self.binder_index.shift_out(1);
1008 result
1009 }
1010
1011 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1012 match *t.kind() {
1013 // FIXME(chalk): currently we convert params to placeholders starting at
1014 // index `0`. To support placeholders, we'll actually need to do a
1015 // first pass to collect placeholders. Then we can insert params after.
1016 ty::Placeholder(_) => unimplemented!(),
1017 ty::Param(param) => match self.list.iter().position(|r| r == &param) {
1018 Some(idx) => self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
1019 universe: ty::UniverseIndex::from_usize(0),
1020 name: ty::BoundVar::from_usize(idx),
1021 })),
1022 None => {
1023 self.list.push(param);
1024 let idx = self.list.len() - 1 + self.next_ty_placeholder;
1025 self.params.insert(idx, param);
1026 self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
1027 universe: ty::UniverseIndex::from_usize(0),
1028 name: ty::BoundVar::from_usize(idx),
1029 }))
1030 }
1031 },
1032
1033 _ => t.super_fold_with(self),
1034 }
1035 }
1036
1037 fn fold_region(&mut self, r: Region<'tcx>) -> Region<'tcx> {
1038 match r {
1039 // FIXME(chalk) - jackh726 - this currently isn't hit in any tests.
1040 // This covers any region variables in a goal, right?
1041 ty::ReEarlyBound(_re) => match self.named_regions.get(&_re.def_id) {
1042 Some(idx) => self.tcx.mk_region(RegionKind::ReLateBound(
1043 self.binder_index,
1044 BoundRegion::BrAnon(*idx),
1045 )),
1046 None => {
1047 let idx = self.named_regions.len() as u32;
1048 self.named_regions.insert(_re.def_id, idx);
1049 self.tcx.mk_region(RegionKind::ReLateBound(
1050 self.binder_index,
1051 BoundRegion::BrAnon(idx),
1052 ))
1053 }
1054 },
1055
1056 _ => r.super_fold_with(self),
1057 }
1058 }
1059 }
1060
1061 /// Used to collect `Placeholder`s.
1062 crate struct PlaceholdersCollector {
1063 universe_index: ty::UniverseIndex,
1064 crate next_ty_placeholder: usize,
1065 crate next_anon_region_placeholder: u32,
1066 }
1067
1068 impl PlaceholdersCollector {
1069 crate fn new() -> Self {
1070 PlaceholdersCollector {
1071 universe_index: ty::UniverseIndex::ROOT,
1072 next_ty_placeholder: 0,
1073 next_anon_region_placeholder: 0,
1074 }
1075 }
1076 }
1077
1078 impl<'tcx> TypeVisitor<'tcx> for PlaceholdersCollector {
1079 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<()> {
1080 match t.kind() {
1081 ty::Placeholder(p) if p.universe == self.universe_index => {
1082 self.next_ty_placeholder = self.next_ty_placeholder.max(p.name.as_usize() + 1);
1083 }
1084
1085 _ => (),
1086 };
1087
1088 t.super_visit_with(self)
1089 }
1090
1091 fn visit_region(&mut self, r: Region<'tcx>) -> ControlFlow<()> {
1092 match r {
1093 ty::RePlaceholder(p) if p.universe == self.universe_index => {
1094 if let ty::BoundRegion::BrAnon(anon) = p.name {
1095 self.next_anon_region_placeholder = self.next_anon_region_placeholder.max(anon);
1096 }
1097 }
1098
1099 _ => (),
1100 };
1101
1102 r.super_visit_with(self)
1103 }
1104 }
1105
1106 /// Used to substitute specific `Regions`s with placeholders.
1107 crate struct RegionsSubstitutor<'tcx> {
1108 tcx: TyCtxt<'tcx>,
1109 reempty_placeholder: ty::Region<'tcx>,
1110 }
1111
1112 impl<'tcx> RegionsSubstitutor<'tcx> {
1113 crate fn new(tcx: TyCtxt<'tcx>, reempty_placeholder: ty::Region<'tcx>) -> Self {
1114 RegionsSubstitutor { tcx, reempty_placeholder }
1115 }
1116 }
1117
1118 impl<'tcx> TypeFolder<'tcx> for RegionsSubstitutor<'tcx> {
1119 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1120 self.tcx
1121 }
1122
1123 fn fold_region(&mut self, r: Region<'tcx>) -> Region<'tcx> {
1124 match r {
1125 ty::ReEmpty(ui) => {
1126 assert_eq!(ui.as_usize(), 0);
1127 self.reempty_placeholder
1128 }
1129
1130 _ => r.super_fold_with(self),
1131 }
1132 }
1133 }