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