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