1 //! Contains the logic to lower rustc types into Chalk types
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
9 //! Much of the `Ty` lowering is 1:1 with Chalk. (Or will be eventually). A
10 //! helpful table for what types lower to what can be found in the
11 //! [Chalk book](http://rust-lang.github.io/chalk/book/types/rust_types.html).
12 //! The most notable difference lies with `Param`s. To convert from rustc to
13 //! Chalk, we eagerly and deeply convert `Param`s to placeholders (in goals) or
14 //! bound variables (for clause generation through functions in `db`).
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.
24 //! ## `Const` lowering
25 //! Chalk doesn't handle consts currently, so consts are currently lowered to
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`.
34 use rustc_middle::traits::{
35 ChalkEnvironmentAndGoal, ChalkEnvironmentClause, ChalkRustInterner as RustInterner,
37 use rustc_middle::ty::fold::TypeFolder;
38 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
39 use rustc_middle::ty::{
40 self, Binder, BoundRegion, Region, RegionKind, Ty, TyCtxt, TyKind, TypeFoldable, TypeVisitor,
42 use rustc_span::def_id::DefId;
44 use std::collections::btree_map::{BTreeMap, Entry};
46 use chalk_ir::fold::shift::Shift;
48 /// Essentially an `Into` with a `&RustInterner` parameter
49 crate trait LowerInto<'tcx, T> {
50 /// Lower a rustc construct (e.g., `ty::TraitPredicate`) to a chalk type, consuming `self`.
51 fn lower_into(self, interner: &RustInterner<'tcx>) -> T;
54 impl<'tcx> LowerInto<'tcx, chalk_ir::Substitution<RustInterner<'tcx>>> for SubstsRef<'tcx> {
57 interner: &RustInterner<'tcx>,
58 ) -> chalk_ir::Substitution<RustInterner<'tcx>> {
59 chalk_ir::Substitution::from(interner, self.iter().map(|s| s.lower_into(interner)))
63 impl<'tcx> LowerInto<'tcx, chalk_ir::AliasTy<RustInterner<'tcx>>> for ty::ProjectionTy<'tcx> {
64 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::AliasTy<RustInterner<'tcx>> {
65 chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy {
66 associated_ty_id: chalk_ir::AssocTypeId(self.item_def_id),
67 substitution: self.substs.lower_into(interner),
72 impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment<chalk_ir::Goal<RustInterner<'tcx>>>>
73 for ChalkEnvironmentAndGoal<'tcx>
77 interner: &RustInterner<'tcx>,
78 ) -> chalk_ir::InEnvironment<chalk_ir::Goal<RustInterner<'tcx>>> {
79 let clauses = self.environment.into_iter().filter_map(|clause| match clause {
80 ChalkEnvironmentClause::Predicate(predicate) => {
81 // FIXME(chalk): forall
82 match predicate.bound_atom(interner.tcx).skip_binder() {
83 ty::PredicateAtom::Trait(predicate, _) => {
84 let predicate = ty::Binder::bind(predicate);
85 let (predicate, binders, _named_regions) =
86 collect_bound_vars(interner, interner.tcx, &predicate);
89 chalk_ir::ProgramClauseData(chalk_ir::Binders::new(
91 chalk_ir::ProgramClauseImplication {
92 consequence: chalk_ir::DomainGoal::FromEnv(
93 chalk_ir::FromEnv::Trait(
94 predicate.trait_ref.lower_into(interner),
97 conditions: chalk_ir::Goals::new(interner),
98 priority: chalk_ir::ClausePriority::High,
104 ty::PredicateAtom::RegionOutlives(predicate) => {
105 let predicate = ty::Binder::bind(predicate);
106 let (predicate, binders, _named_regions) =
107 collect_bound_vars(interner, interner.tcx, &predicate);
110 chalk_ir::ProgramClauseData(chalk_ir::Binders::new(
112 chalk_ir::ProgramClauseImplication {
113 consequence: chalk_ir::DomainGoal::Holds(
114 chalk_ir::WhereClause::LifetimeOutlives(
115 chalk_ir::LifetimeOutlives {
116 a: predicate.0.lower_into(interner),
117 b: predicate.1.lower_into(interner),
121 conditions: chalk_ir::Goals::new(interner),
122 priority: chalk_ir::ClausePriority::High,
128 // FIXME(chalk): need to add TypeOutlives
129 ty::PredicateAtom::TypeOutlives(_) => None,
130 ty::PredicateAtom::Projection(predicate) => {
131 let predicate = ty::Binder::bind(predicate);
132 let (predicate, binders, _named_regions) =
133 collect_bound_vars(interner, interner.tcx, &predicate);
136 chalk_ir::ProgramClauseData(chalk_ir::Binders::new(
138 chalk_ir::ProgramClauseImplication {
139 consequence: chalk_ir::DomainGoal::Holds(
140 chalk_ir::WhereClause::AliasEq(
141 predicate.lower_into(interner),
144 conditions: chalk_ir::Goals::new(interner),
145 priority: chalk_ir::ClausePriority::High,
151 ty::PredicateAtom::WellFormed(..)
152 | ty::PredicateAtom::ObjectSafe(..)
153 | ty::PredicateAtom::ClosureKind(..)
154 | ty::PredicateAtom::Subtype(..)
155 | ty::PredicateAtom::ConstEvaluatable(..)
156 | ty::PredicateAtom::ConstEquate(..) => {
157 bug!("unexpected predicate {}", predicate)
161 ChalkEnvironmentClause::TypeFromEnv(ty) => Some(
162 chalk_ir::ProgramClauseData(chalk_ir::Binders::new(
163 chalk_ir::VariableKinds::new(interner),
164 chalk_ir::ProgramClauseImplication {
165 consequence: chalk_ir::DomainGoal::FromEnv(chalk_ir::FromEnv::Ty(
166 ty.lower_into(interner).shifted_in(interner),
168 conditions: chalk_ir::Goals::new(interner),
169 priority: chalk_ir::ClausePriority::High,
176 let goal: chalk_ir::GoalData<RustInterner<'tcx>> = self.goal.lower_into(&interner);
177 chalk_ir::InEnvironment {
178 environment: chalk_ir::Environment {
179 clauses: chalk_ir::ProgramClauses::from(&interner, clauses),
181 goal: goal.intern(&interner),
186 impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData<RustInterner<'tcx>>> for ty::Predicate<'tcx> {
187 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData<RustInterner<'tcx>> {
188 // FIXME(chalk): forall
189 match self.bound_atom(interner.tcx).skip_binder() {
190 ty::PredicateAtom::Trait(predicate, _) => {
191 ty::Binder::bind(predicate).lower_into(interner)
193 ty::PredicateAtom::RegionOutlives(predicate) => {
194 let predicate = ty::Binder::bind(predicate);
195 let (predicate, binders, _named_regions) =
196 collect_bound_vars(interner, interner.tcx, &predicate);
198 chalk_ir::GoalData::Quantified(
199 chalk_ir::QuantifierKind::ForAll,
200 chalk_ir::Binders::new(
202 chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
203 chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives {
204 a: predicate.0.lower_into(interner),
205 b: predicate.1.lower_into(interner),
212 // FIXME(chalk): TypeOutlives
213 ty::PredicateAtom::TypeOutlives(_predicate) => {
214 chalk_ir::GoalData::All(chalk_ir::Goals::new(interner))
216 ty::PredicateAtom::Projection(predicate) => {
217 ty::Binder::bind(predicate).lower_into(interner)
219 ty::PredicateAtom::WellFormed(arg) => match arg.unpack() {
220 GenericArgKind::Type(ty) => match ty.kind {
221 // FIXME(chalk): In Chalk, a placeholder is WellFormed if it
222 // `FromEnv`. However, when we "lower" Params, we don't update
224 ty::Placeholder(..) => chalk_ir::GoalData::All(chalk_ir::Goals::new(interner)),
227 let (ty, binders, _named_regions) =
228 collect_bound_vars(interner, interner.tcx, &ty::Binder::bind(ty));
230 chalk_ir::GoalData::Quantified(
231 chalk_ir::QuantifierKind::ForAll,
232 chalk_ir::Binders::new(
234 chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::WellFormed(
235 chalk_ir::WellFormed::Ty(ty.lower_into(interner)),
242 // FIXME(chalk): handle well formed consts
243 GenericArgKind::Const(..) => {
244 chalk_ir::GoalData::All(chalk_ir::Goals::new(interner))
246 GenericArgKind::Lifetime(lt) => bug!("unexpect well formed predicate: {:?}", lt),
249 ty::PredicateAtom::ObjectSafe(t) => chalk_ir::GoalData::DomainGoal(
250 chalk_ir::DomainGoal::ObjectSafe(chalk_ir::TraitId(t)),
253 // FIXME(chalk): other predicates
255 // We can defer this, but ultimately we'll want to express
256 // some of these in terms of chalk operations.
257 ty::PredicateAtom::ClosureKind(..)
258 | ty::PredicateAtom::Subtype(..)
259 | ty::PredicateAtom::ConstEvaluatable(..)
260 | ty::PredicateAtom::ConstEquate(..) => {
261 chalk_ir::GoalData::All(chalk_ir::Goals::new(interner))
267 impl<'tcx> LowerInto<'tcx, chalk_ir::TraitRef<RustInterner<'tcx>>>
268 for rustc_middle::ty::TraitRef<'tcx>
270 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::TraitRef<RustInterner<'tcx>> {
272 trait_id: chalk_ir::TraitId(self.def_id),
273 substitution: self.substs.lower_into(interner),
278 impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData<RustInterner<'tcx>>>
279 for ty::PolyTraitPredicate<'tcx>
281 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData<RustInterner<'tcx>> {
282 let (ty, binders, _named_regions) = collect_bound_vars(interner, interner.tcx, &self);
284 chalk_ir::GoalData::Quantified(
285 chalk_ir::QuantifierKind::ForAll,
286 chalk_ir::Binders::new(
288 chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
289 chalk_ir::WhereClause::Implemented(ty.trait_ref.lower_into(interner)),
297 impl<'tcx> LowerInto<'tcx, chalk_ir::AliasEq<RustInterner<'tcx>>>
298 for rustc_middle::ty::ProjectionPredicate<'tcx>
300 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::AliasEq<RustInterner<'tcx>> {
302 ty: self.ty.lower_into(interner),
303 alias: self.projection_ty.lower_into(interner),
308 impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData<RustInterner<'tcx>>>
309 for ty::PolyProjectionPredicate<'tcx>
311 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData<RustInterner<'tcx>> {
312 let (ty, binders, _named_regions) = collect_bound_vars(interner, interner.tcx, &self);
314 chalk_ir::GoalData::Quantified(
315 chalk_ir::QuantifierKind::ForAll,
316 chalk_ir::Binders::new(
318 chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
319 chalk_ir::WhereClause::AliasEq(ty.lower_into(interner)),
327 impl<'tcx> LowerInto<'tcx, chalk_ir::Ty<RustInterner<'tcx>>> for Ty<'tcx> {
328 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Ty<RustInterner<'tcx>> {
329 use chalk_ir::TyData;
333 let empty = || chalk_ir::Substitution::empty(interner);
335 |def_id| chalk_ir::TypeName::Adt(chalk_ir::AdtId(interner.tcx.adt_def(def_id)));
336 let apply = |name, substitution| {
337 TyData::Apply(chalk_ir::ApplicationTy { name, substitution }).intern(interner)
339 let int = |i| apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Int(i)), empty());
340 let uint = |i| apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Uint(i)), empty());
341 let float = |f| apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Float(f)), empty());
344 Bool => apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Bool), empty()),
345 Char => apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Char), empty()),
346 Int(ty) => match ty {
347 ast::IntTy::Isize => int(chalk_ir::IntTy::Isize),
348 ast::IntTy::I8 => int(chalk_ir::IntTy::I8),
349 ast::IntTy::I16 => int(chalk_ir::IntTy::I16),
350 ast::IntTy::I32 => int(chalk_ir::IntTy::I32),
351 ast::IntTy::I64 => int(chalk_ir::IntTy::I64),
352 ast::IntTy::I128 => int(chalk_ir::IntTy::I128),
354 Uint(ty) => match ty {
355 ast::UintTy::Usize => uint(chalk_ir::UintTy::Usize),
356 ast::UintTy::U8 => uint(chalk_ir::UintTy::U8),
357 ast::UintTy::U16 => uint(chalk_ir::UintTy::U16),
358 ast::UintTy::U32 => uint(chalk_ir::UintTy::U32),
359 ast::UintTy::U64 => uint(chalk_ir::UintTy::U64),
360 ast::UintTy::U128 => uint(chalk_ir::UintTy::U128),
362 Float(ty) => match ty {
363 ast::FloatTy::F32 => float(chalk_ir::FloatTy::F32),
364 ast::FloatTy::F64 => float(chalk_ir::FloatTy::F64),
366 Adt(def, substs) => apply(struct_ty(def.did), substs.lower_into(interner)),
367 Foreign(_def_id) => unimplemented!(),
368 Str => apply(chalk_ir::TypeName::Str, empty()),
370 let value = match len.val {
371 ty::ConstKind::Value(val) => {
372 chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: val })
374 ty::ConstKind::Bound(db, bound) => {
375 chalk_ir::ConstValue::BoundVar(chalk_ir::BoundVar::new(
376 chalk_ir::DebruijnIndex::new(db.as_u32()),
380 _ => unimplemented!("Const not implemented. {:?}", len.val),
383 chalk_ir::TypeName::Array,
384 chalk_ir::Substitution::from(
387 chalk_ir::GenericArgData::Ty(ty.lower_into(interner)).intern(interner),
388 chalk_ir::GenericArgData::Const(
389 chalk_ir::ConstData { ty: len.ty.lower_into(interner), value }
398 chalk_ir::TypeName::Slice,
399 chalk_ir::Substitution::from1(
401 chalk_ir::GenericArgData::Ty(ty.lower_into(interner)).intern(interner),
405 let name = match ptr.mutbl {
406 ast::Mutability::Mut => chalk_ir::TypeName::Raw(chalk_ir::Mutability::Mut),
407 ast::Mutability::Not => chalk_ir::TypeName::Raw(chalk_ir::Mutability::Not),
409 apply(name, chalk_ir::Substitution::from1(interner, ptr.ty.lower_into(interner)))
411 Ref(region, ty, mutability) => {
412 let name = match mutability {
413 ast::Mutability::Mut => chalk_ir::TypeName::Ref(chalk_ir::Mutability::Mut),
414 ast::Mutability::Not => chalk_ir::TypeName::Ref(chalk_ir::Mutability::Not),
418 chalk_ir::Substitution::from(
421 chalk_ir::GenericArgData::Lifetime(region.lower_into(interner))
423 chalk_ir::GenericArgData::Ty(ty.lower_into(interner)).intern(interner),
428 FnDef(def_id, substs) => apply(
429 chalk_ir::TypeName::FnDef(chalk_ir::FnDefId(def_id)),
430 substs.lower_into(interner),
433 let (inputs_and_outputs, binders, _named_regions) =
434 collect_bound_vars(interner, interner.tcx, &sig.inputs_and_output());
435 TyData::Function(chalk_ir::Fn {
436 num_binders: binders.len(interner),
437 substitution: chalk_ir::Substitution::from(
439 inputs_and_outputs.iter().map(|ty| {
440 chalk_ir::GenericArgData::Ty(ty.lower_into(interner)).intern(interner)
446 Dynamic(predicates, region) => TyData::Dyn(chalk_ir::DynTy {
447 bounds: predicates.lower_into(interner),
448 lifetime: region.lower_into(interner),
451 Closure(def_id, substs) => apply(
452 chalk_ir::TypeName::Closure(chalk_ir::ClosureId(def_id)),
453 substs.lower_into(interner),
455 Generator(_def_id, _substs, _) => unimplemented!(),
456 GeneratorWitness(_) => unimplemented!(),
457 Never => apply(chalk_ir::TypeName::Never, empty()),
459 apply(chalk_ir::TypeName::Tuple(substs.len()), substs.lower_into(interner))
461 Projection(proj) => TyData::Alias(proj.lower_into(interner)).intern(interner),
462 Opaque(def_id, substs) => {
463 TyData::Alias(chalk_ir::AliasTy::Opaque(chalk_ir::OpaqueTy {
464 opaque_ty_id: chalk_ir::OpaqueTyId(def_id),
465 substitution: substs.lower_into(interner),
469 // This should have been done eagerly prior to this, and all Params
470 // should have been substituted to placeholders
471 Param(_) => panic!("Lowering Param when not expected."),
472 Bound(db, bound) => TyData::BoundVar(chalk_ir::BoundVar::new(
473 chalk_ir::DebruijnIndex::new(db.as_u32()),
477 Placeholder(_placeholder) => TyData::Placeholder(chalk_ir::PlaceholderIndex {
478 ui: chalk_ir::UniverseIndex { counter: _placeholder.universe.as_usize() },
479 idx: _placeholder.name.as_usize(),
482 Infer(_infer) => unimplemented!(),
483 Error(_) => apply(chalk_ir::TypeName::Error, empty()),
488 impl<'tcx> LowerInto<'tcx, chalk_ir::Lifetime<RustInterner<'tcx>>> for Region<'tcx> {
489 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Lifetime<RustInterner<'tcx>> {
490 use rustc_middle::ty::RegionKind::*;
494 panic!("Should have already been substituted.");
496 ReLateBound(db, br) => match br {
497 ty::BoundRegion::BrAnon(var) => {
498 chalk_ir::LifetimeData::BoundVar(chalk_ir::BoundVar::new(
499 chalk_ir::DebruijnIndex::new(db.as_u32()),
504 ty::BoundRegion::BrNamed(_def_id, _name) => unimplemented!(),
505 ty::BrEnv => unimplemented!(),
507 ReFree(_) => unimplemented!(),
508 // FIXME(chalk): need to handle ReStatic
509 ReStatic => unimplemented!(),
510 ReVar(_) => unimplemented!(),
511 RePlaceholder(placeholder_region) => {
512 chalk_ir::LifetimeData::Placeholder(chalk_ir::PlaceholderIndex {
513 ui: chalk_ir::UniverseIndex { counter: placeholder_region.universe.index() },
518 ReEmpty(_) => unimplemented!(),
519 // FIXME(chalk): need to handle ReErased
520 ReErased => unimplemented!(),
525 impl<'tcx> LowerInto<'tcx, chalk_ir::GenericArg<RustInterner<'tcx>>> for GenericArg<'tcx> {
526 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GenericArg<RustInterner<'tcx>> {
527 match self.unpack() {
528 ty::subst::GenericArgKind::Type(ty) => {
529 chalk_ir::GenericArgData::Ty(ty.lower_into(interner))
531 ty::subst::GenericArgKind::Lifetime(lifetime) => {
532 chalk_ir::GenericArgData::Lifetime(lifetime.lower_into(interner))
534 ty::subst::GenericArgKind::Const(_) => chalk_ir::GenericArgData::Ty(
535 chalk_ir::TyData::Apply(chalk_ir::ApplicationTy {
536 name: chalk_ir::TypeName::Tuple(0),
537 substitution: chalk_ir::Substitution::empty(interner),
546 // We lower into an Option here since there are some predicates which Chalk
547 // doesn't have a representation for yet (as a `WhereClause`), but are so common
548 // that we just are accepting the unsoundness for now. The `Option` will
549 // eventually be removed.
550 impl<'tcx> LowerInto<'tcx, Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>>>
551 for ty::Predicate<'tcx>
555 interner: &RustInterner<'tcx>,
556 ) -> Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>> {
557 // FIXME(chalk): forall
558 match self.bound_atom(interner.tcx).skip_binder() {
559 ty::PredicateAtom::Trait(predicate, _) => {
560 let predicate = ty::Binder::bind(predicate);
561 let (predicate, binders, _named_regions) =
562 collect_bound_vars(interner, interner.tcx, &predicate);
564 Some(chalk_ir::Binders::new(
566 chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner)),
569 ty::PredicateAtom::RegionOutlives(predicate) => {
570 let predicate = ty::Binder::bind(predicate);
571 let (predicate, binders, _named_regions) =
572 collect_bound_vars(interner, interner.tcx, &predicate);
574 Some(chalk_ir::Binders::new(
576 chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives {
577 a: predicate.0.lower_into(interner),
578 b: predicate.1.lower_into(interner),
582 ty::PredicateAtom::TypeOutlives(_predicate) => None,
583 ty::PredicateAtom::Projection(_predicate) => None,
584 ty::PredicateAtom::WellFormed(_ty) => None,
586 ty::PredicateAtom::ObjectSafe(..)
587 | ty::PredicateAtom::ClosureKind(..)
588 | ty::PredicateAtom::Subtype(..)
589 | ty::PredicateAtom::ConstEvaluatable(..)
590 | ty::PredicateAtom::ConstEquate(..) => bug!("unexpected predicate {}", &self),
595 impl<'tcx> LowerInto<'tcx, chalk_ir::Binders<chalk_ir::QuantifiedWhereClauses<RustInterner<'tcx>>>>
596 for Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>
600 interner: &RustInterner<'tcx>,
601 ) -> chalk_ir::Binders<chalk_ir::QuantifiedWhereClauses<RustInterner<'tcx>>> {
602 let (predicates, binders, _named_regions) =
603 collect_bound_vars(interner, interner.tcx, &self);
604 let where_clauses = predicates.into_iter().map(|predicate| match predicate {
605 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef { def_id, substs }) => {
606 chalk_ir::Binders::new(
607 chalk_ir::VariableKinds::new(interner),
608 chalk_ir::WhereClause::Implemented(chalk_ir::TraitRef {
609 trait_id: chalk_ir::TraitId(def_id),
610 substitution: substs.lower_into(interner),
614 ty::ExistentialPredicate::Projection(_predicate) => unimplemented!(),
615 ty::ExistentialPredicate::AutoTrait(def_id) => chalk_ir::Binders::new(
616 chalk_ir::VariableKinds::new(interner),
617 chalk_ir::WhereClause::Implemented(chalk_ir::TraitRef {
618 trait_id: chalk_ir::TraitId(def_id),
619 substitution: chalk_ir::Substitution::empty(interner),
623 let value = chalk_ir::QuantifiedWhereClauses::from(interner, where_clauses);
624 chalk_ir::Binders::new(binders, value)
628 /// To collect bound vars, we have to do two passes. In the first pass, we
629 /// collect all `BoundRegion`s and `ty::Bound`s. In the second pass, we then
630 /// replace `BrNamed` into `BrAnon`. The two separate passes are important,
631 /// since we can only replace `BrNamed` with `BrAnon`s with indices *after* all
632 /// "real" `BrAnon`s.
634 /// It's important to note that because of prior substitution, we may have
635 /// late-bound regions, even outside of fn contexts, since this is the best way
636 /// to prep types for chalk lowering.
637 crate fn collect_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>>(
638 interner: &RustInterner<'tcx>,
641 ) -> (T, chalk_ir::VariableKinds<RustInterner<'tcx>>, BTreeMap<DefId, u32>) {
642 let mut bound_vars_collector = BoundVarsCollector::new();
643 ty.as_ref().skip_binder().visit_with(&mut bound_vars_collector);
644 let mut parameters = bound_vars_collector.parameters;
645 let named_parameters: BTreeMap<DefId, u32> = bound_vars_collector
649 .map(|(i, def_id)| (def_id, (i + parameters.len()) as u32))
652 let mut bound_var_substitutor = NamedBoundVarSubstitutor::new(tcx, &named_parameters);
653 let new_ty = ty.as_ref().skip_binder().fold_with(&mut bound_var_substitutor);
655 for var in named_parameters.values() {
656 parameters.insert(*var, chalk_ir::VariableKind::Lifetime);
659 (0..parameters.len()).for_each(|i| {
662 .or_else(|| bug!("Skipped bound var index: ty={:?}, parameters={:?}", ty, parameters));
665 let binders = chalk_ir::VariableKinds::from(interner, parameters.into_iter().map(|(_, v)| v));
667 (new_ty, binders, named_parameters)
670 crate struct BoundVarsCollector<'tcx> {
671 binder_index: ty::DebruijnIndex,
672 crate parameters: BTreeMap<u32, chalk_ir::VariableKind<RustInterner<'tcx>>>,
673 crate named_parameters: Vec<DefId>,
676 impl<'tcx> BoundVarsCollector<'tcx> {
677 crate fn new() -> Self {
679 binder_index: ty::INNERMOST,
680 parameters: BTreeMap::new(),
681 named_parameters: vec![],
686 impl<'tcx> TypeVisitor<'tcx> for BoundVarsCollector<'tcx> {
687 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
688 self.binder_index.shift_in(1);
689 let result = t.super_visit_with(self);
690 self.binder_index.shift_out(1);
694 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
696 ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
697 match self.parameters.entry(bound_ty.var.as_u32()) {
698 Entry::Vacant(entry) => {
699 entry.insert(chalk_ir::VariableKind::Ty(chalk_ir::TyKind::General));
701 Entry::Occupied(entry) => match entry.get() {
702 chalk_ir::VariableKind::Ty(_) => {}
711 t.super_visit_with(self)
714 fn visit_region(&mut self, r: Region<'tcx>) -> bool {
716 ty::ReLateBound(index, br) if *index == self.binder_index => match br {
717 ty::BoundRegion::BrNamed(def_id, _name) => {
718 if self.named_parameters.iter().find(|d| *d == def_id).is_none() {
719 self.named_parameters.push(*def_id);
723 ty::BoundRegion::BrAnon(var) => match self.parameters.entry(*var) {
724 Entry::Vacant(entry) => {
725 entry.insert(chalk_ir::VariableKind::Lifetime);
727 Entry::Occupied(entry) => match entry.get() {
728 chalk_ir::VariableKind::Lifetime => {}
733 ty::BrEnv => unimplemented!(),
736 ty::ReEarlyBound(_re) => {
737 // FIXME(chalk): jackh726 - I think we should always have already
738 // substituted away `ReEarlyBound`s for `ReLateBound`s, but need to confirm.
745 r.super_visit_with(self)
749 /// This is used to replace `BoundRegion::BrNamed` with `BoundRegion::BrAnon`.
750 /// Note: we assume that we will always have room for more bound vars. (i.e. we
751 /// won't ever hit the `u32` limit in `BrAnon`s).
752 struct NamedBoundVarSubstitutor<'a, 'tcx> {
754 binder_index: ty::DebruijnIndex,
755 named_parameters: &'a BTreeMap<DefId, u32>,
758 impl<'a, 'tcx> NamedBoundVarSubstitutor<'a, 'tcx> {
759 fn new(tcx: TyCtxt<'tcx>, named_parameters: &'a BTreeMap<DefId, u32>) -> Self {
760 NamedBoundVarSubstitutor { tcx, binder_index: ty::INNERMOST, named_parameters }
764 impl<'a, 'tcx> TypeFolder<'tcx> for NamedBoundVarSubstitutor<'a, 'tcx> {
765 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
769 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> Binder<T> {
770 self.binder_index.shift_in(1);
771 let result = t.super_fold_with(self);
772 self.binder_index.shift_out(1);
776 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
777 t.super_fold_with(self)
780 fn fold_region(&mut self, r: Region<'tcx>) -> Region<'tcx> {
782 ty::ReLateBound(index, br) if *index == self.binder_index => match br {
783 ty::BoundRegion::BrNamed(def_id, _name) => {
784 match self.named_parameters.get(def_id) {
786 return self.tcx.mk_region(RegionKind::ReLateBound(
788 BoundRegion::BrAnon(*idx),
791 None => panic!("Missing `BrNamed`."),
794 ty::BrEnv => unimplemented!(),
795 ty::BoundRegion::BrAnon(_) => {}
800 r.super_fold_with(self)
804 /// Used to substitute `Param`s with placeholders. We do this since Chalk
805 /// have a notion of `Param`s.
806 crate struct ParamsSubstitutor<'tcx> {
808 binder_index: ty::DebruijnIndex,
809 list: Vec<rustc_middle::ty::ParamTy>,
810 crate params: rustc_data_structures::fx::FxHashMap<usize, rustc_middle::ty::ParamTy>,
811 crate named_regions: BTreeMap<DefId, u32>,
814 impl<'tcx> ParamsSubstitutor<'tcx> {
815 crate fn new(tcx: TyCtxt<'tcx>) -> Self {
818 binder_index: ty::INNERMOST,
820 params: rustc_data_structures::fx::FxHashMap::default(),
821 named_regions: BTreeMap::default(),
826 impl<'tcx> TypeFolder<'tcx> for ParamsSubstitutor<'tcx> {
827 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
831 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> Binder<T> {
832 self.binder_index.shift_in(1);
833 let result = t.super_fold_with(self);
834 self.binder_index.shift_out(1);
838 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
840 // FIXME(chalk): currently we convert params to placeholders starting at
841 // index `0`. To support placeholders, we'll actually need to do a
842 // first pass to collect placeholders. Then we can insert params after.
843 ty::Placeholder(_) => unimplemented!(),
844 ty::Param(param) => match self.list.iter().position(|r| r == ¶m) {
845 Some(_idx) => self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
846 universe: ty::UniverseIndex::from_usize(0),
847 name: ty::BoundVar::from_usize(_idx),
850 self.list.push(param);
851 let idx = self.list.len() - 1;
852 self.params.insert(idx, param);
853 self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
854 universe: ty::UniverseIndex::from_usize(0),
855 name: ty::BoundVar::from_usize(idx),
860 _ => t.super_fold_with(self),
864 fn fold_region(&mut self, r: Region<'tcx>) -> Region<'tcx> {
866 // FIXME(chalk) - jackh726 - this currently isn't hit in any tests.
867 // This covers any region variables in a goal, right?
868 ty::ReEarlyBound(_re) => match self.named_regions.get(&_re.def_id) {
869 Some(idx) => self.tcx.mk_region(RegionKind::ReLateBound(
871 BoundRegion::BrAnon(*idx),
874 let idx = self.named_regions.len() as u32;
875 self.named_regions.insert(_re.def_id, idx);
876 self.tcx.mk_region(RegionKind::ReLateBound(
878 BoundRegion::BrAnon(idx),
883 _ => r.super_fold_with(self),