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