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