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 match predicate.kind() {
82 ty::PredicateKind::Trait(predicate, _) => {
83 let (predicate, binders, _named_regions) =
84 collect_bound_vars(interner, interner.tcx, predicate);
87 chalk_ir::ProgramClauseData(chalk_ir::Binders::new(
89 chalk_ir::ProgramClauseImplication {
90 consequence: chalk_ir::DomainGoal::FromEnv(
91 chalk_ir::FromEnv::Trait(
92 predicate.trait_ref.lower_into(interner),
95 conditions: chalk_ir::Goals::new(interner),
96 priority: chalk_ir::ClausePriority::High,
102 ty::PredicateKind::RegionOutlives(predicate) => {
103 let (predicate, binders, _named_regions) =
104 collect_bound_vars(interner, interner.tcx, predicate);
107 chalk_ir::ProgramClauseData(chalk_ir::Binders::new(
109 chalk_ir::ProgramClauseImplication {
110 consequence: chalk_ir::DomainGoal::Holds(
111 chalk_ir::WhereClause::LifetimeOutlives(
112 chalk_ir::LifetimeOutlives {
113 a: predicate.0.lower_into(interner),
114 b: predicate.1.lower_into(interner),
118 conditions: chalk_ir::Goals::new(interner),
119 priority: chalk_ir::ClausePriority::High,
125 // FIXME(chalk): need to add TypeOutlives
126 ty::PredicateKind::TypeOutlives(_) => None,
127 ty::PredicateKind::Projection(predicate) => {
128 let (predicate, binders, _named_regions) =
129 collect_bound_vars(interner, interner.tcx, predicate);
132 chalk_ir::ProgramClauseData(chalk_ir::Binders::new(
134 chalk_ir::ProgramClauseImplication {
135 consequence: chalk_ir::DomainGoal::Holds(
136 chalk_ir::WhereClause::AliasEq(
137 predicate.lower_into(interner),
140 conditions: chalk_ir::Goals::new(interner),
141 priority: chalk_ir::ClausePriority::High,
147 ty::PredicateKind::WellFormed(..)
148 | ty::PredicateKind::ObjectSafe(..)
149 | ty::PredicateKind::ClosureKind(..)
150 | ty::PredicateKind::Subtype(..)
151 | ty::PredicateKind::ConstEvaluatable(..)
152 | ty::PredicateKind::ConstEquate(..) => {
153 bug!("unexpected predicate {}", predicate)
157 ChalkEnvironmentClause::TypeFromEnv(ty) => Some(
158 chalk_ir::ProgramClauseData(chalk_ir::Binders::new(
159 chalk_ir::VariableKinds::new(interner),
160 chalk_ir::ProgramClauseImplication {
161 consequence: chalk_ir::DomainGoal::FromEnv(chalk_ir::FromEnv::Ty(
162 ty.lower_into(interner).shifted_in(interner),
164 conditions: chalk_ir::Goals::new(interner),
165 priority: chalk_ir::ClausePriority::High,
172 let goal: chalk_ir::GoalData<RustInterner<'tcx>> = self.goal.lower_into(&interner);
173 chalk_ir::InEnvironment {
174 environment: chalk_ir::Environment {
175 clauses: chalk_ir::ProgramClauses::from(&interner, clauses),
177 goal: goal.intern(&interner),
182 impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData<RustInterner<'tcx>>> for ty::Predicate<'tcx> {
183 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData<RustInterner<'tcx>> {
185 ty::PredicateKind::Trait(predicate, _) => predicate.lower_into(interner),
186 ty::PredicateKind::RegionOutlives(predicate) => {
187 let (predicate, binders, _named_regions) =
188 collect_bound_vars(interner, interner.tcx, predicate);
190 chalk_ir::GoalData::Quantified(
191 chalk_ir::QuantifierKind::ForAll,
192 chalk_ir::Binders::new(
194 chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
195 chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives {
196 a: predicate.0.lower_into(interner),
197 b: predicate.1.lower_into(interner),
204 // FIXME(chalk): TypeOutlives
205 ty::PredicateKind::TypeOutlives(_predicate) => {
206 chalk_ir::GoalData::All(chalk_ir::Goals::new(interner))
208 ty::PredicateKind::Projection(predicate) => predicate.lower_into(interner),
209 ty::PredicateKind::WellFormed(arg) => match arg.unpack() {
210 GenericArgKind::Type(ty) => match ty.kind {
211 // FIXME(chalk): In Chalk, a placeholder is WellFormed if it
212 // `FromEnv`. However, when we "lower" Params, we don't update
214 ty::Placeholder(..) => chalk_ir::GoalData::All(chalk_ir::Goals::new(interner)),
216 _ => chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::WellFormed(
217 chalk_ir::WellFormed::Ty(ty.lower_into(interner)),
220 // FIXME(chalk): handle well formed consts
221 GenericArgKind::Const(..) => {
222 chalk_ir::GoalData::All(chalk_ir::Goals::new(interner))
224 GenericArgKind::Lifetime(lt) => bug!("unexpect well formed predicate: {:?}", lt),
227 ty::PredicateKind::ObjectSafe(t) => chalk_ir::GoalData::DomainGoal(
228 chalk_ir::DomainGoal::ObjectSafe(chalk_ir::TraitId(*t)),
231 // FIXME(chalk): other predicates
233 // We can defer this, but ultimately we'll want to express
234 // some of these in terms of chalk operations.
235 ty::PredicateKind::ClosureKind(..)
236 | ty::PredicateKind::Subtype(..)
237 | ty::PredicateKind::ConstEvaluatable(..)
238 | ty::PredicateKind::ConstEquate(..) => {
239 chalk_ir::GoalData::All(chalk_ir::Goals::new(interner))
245 impl<'tcx> LowerInto<'tcx, chalk_ir::TraitRef<RustInterner<'tcx>>>
246 for rustc_middle::ty::TraitRef<'tcx>
248 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::TraitRef<RustInterner<'tcx>> {
250 trait_id: chalk_ir::TraitId(self.def_id),
251 substitution: self.substs.lower_into(interner),
256 impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData<RustInterner<'tcx>>>
257 for ty::PolyTraitPredicate<'tcx>
259 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData<RustInterner<'tcx>> {
260 let (ty, binders, _named_regions) = collect_bound_vars(interner, interner.tcx, &self);
262 chalk_ir::GoalData::Quantified(
263 chalk_ir::QuantifierKind::ForAll,
264 chalk_ir::Binders::new(
266 chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
267 chalk_ir::WhereClause::Implemented(ty.trait_ref.lower_into(interner)),
275 impl<'tcx> LowerInto<'tcx, chalk_ir::AliasEq<RustInterner<'tcx>>>
276 for rustc_middle::ty::ProjectionPredicate<'tcx>
278 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::AliasEq<RustInterner<'tcx>> {
280 ty: self.ty.lower_into(interner),
281 alias: self.projection_ty.lower_into(interner),
286 impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData<RustInterner<'tcx>>>
287 for ty::PolyProjectionPredicate<'tcx>
289 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData<RustInterner<'tcx>> {
290 let (ty, binders, _named_regions) = collect_bound_vars(interner, interner.tcx, &self);
292 chalk_ir::GoalData::Quantified(
293 chalk_ir::QuantifierKind::ForAll,
294 chalk_ir::Binders::new(
296 chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
297 chalk_ir::WhereClause::AliasEq(ty.lower_into(interner)),
305 impl<'tcx> LowerInto<'tcx, chalk_ir::Ty<RustInterner<'tcx>>> for Ty<'tcx> {
306 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Ty<RustInterner<'tcx>> {
307 use chalk_ir::TyData;
311 let empty = || chalk_ir::Substitution::empty(interner);
313 |def_id| chalk_ir::TypeName::Adt(chalk_ir::AdtId(interner.tcx.adt_def(def_id)));
314 let apply = |name, substitution| {
315 TyData::Apply(chalk_ir::ApplicationTy { name, substitution }).intern(interner)
317 let int = |i| apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Int(i)), empty());
318 let uint = |i| apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Uint(i)), empty());
319 let float = |f| apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Float(f)), empty());
322 Bool => apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Bool), empty()),
323 Char => apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Char), empty()),
324 Int(ty) => match ty {
325 ast::IntTy::Isize => int(chalk_ir::IntTy::Isize),
326 ast::IntTy::I8 => int(chalk_ir::IntTy::I8),
327 ast::IntTy::I16 => int(chalk_ir::IntTy::I16),
328 ast::IntTy::I32 => int(chalk_ir::IntTy::I32),
329 ast::IntTy::I64 => int(chalk_ir::IntTy::I64),
330 ast::IntTy::I128 => int(chalk_ir::IntTy::I128),
332 Uint(ty) => match ty {
333 ast::UintTy::Usize => uint(chalk_ir::UintTy::Usize),
334 ast::UintTy::U8 => uint(chalk_ir::UintTy::U8),
335 ast::UintTy::U16 => uint(chalk_ir::UintTy::U16),
336 ast::UintTy::U32 => uint(chalk_ir::UintTy::U32),
337 ast::UintTy::U64 => uint(chalk_ir::UintTy::U64),
338 ast::UintTy::U128 => uint(chalk_ir::UintTy::U128),
340 Float(ty) => match ty {
341 ast::FloatTy::F32 => float(chalk_ir::FloatTy::F32),
342 ast::FloatTy::F64 => float(chalk_ir::FloatTy::F64),
344 Adt(def, substs) => apply(struct_ty(def.did), substs.lower_into(interner)),
345 Foreign(_def_id) => unimplemented!(),
346 Str => apply(chalk_ir::TypeName::Str, empty()),
348 let value = match len.val {
349 ty::ConstKind::Value(val) => {
350 chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: val })
352 ty::ConstKind::Bound(db, bound) => {
353 chalk_ir::ConstValue::BoundVar(chalk_ir::BoundVar::new(
354 chalk_ir::DebruijnIndex::new(db.as_u32()),
358 _ => unimplemented!("Const not implemented. {:?}", len.val),
361 chalk_ir::TypeName::Array,
362 chalk_ir::Substitution::from(
365 chalk_ir::GenericArgData::Ty(ty.lower_into(interner)).intern(interner),
366 chalk_ir::GenericArgData::Const(
367 chalk_ir::ConstData { ty: len.ty.lower_into(interner), value }
376 chalk_ir::TypeName::Slice,
377 chalk_ir::Substitution::from1(
379 chalk_ir::GenericArgData::Ty(ty.lower_into(interner)).intern(interner),
383 let name = match ptr.mutbl {
384 ast::Mutability::Mut => chalk_ir::TypeName::Raw(chalk_ir::Mutability::Mut),
385 ast::Mutability::Not => chalk_ir::TypeName::Raw(chalk_ir::Mutability::Not),
387 apply(name, chalk_ir::Substitution::from1(interner, ptr.ty.lower_into(interner)))
389 Ref(region, ty, mutability) => {
390 let name = match mutability {
391 ast::Mutability::Mut => chalk_ir::TypeName::Ref(chalk_ir::Mutability::Mut),
392 ast::Mutability::Not => chalk_ir::TypeName::Ref(chalk_ir::Mutability::Not),
396 chalk_ir::Substitution::from(
399 chalk_ir::GenericArgData::Lifetime(region.lower_into(interner))
401 chalk_ir::GenericArgData::Ty(ty.lower_into(interner)).intern(interner),
406 FnDef(def_id, substs) => apply(
407 chalk_ir::TypeName::FnDef(chalk_ir::FnDefId(def_id)),
408 substs.lower_into(interner),
411 let (inputs_and_outputs, binders, _named_regions) =
412 collect_bound_vars(interner, interner.tcx, &sig.inputs_and_output());
413 TyData::Function(chalk_ir::Fn {
414 num_binders: binders.len(interner),
415 substitution: chalk_ir::Substitution::from(
417 inputs_and_outputs.iter().map(|ty| {
418 chalk_ir::GenericArgData::Ty(ty.lower_into(interner)).intern(interner)
424 Dynamic(predicates, region) => TyData::Dyn(chalk_ir::DynTy {
425 bounds: predicates.lower_into(interner),
426 lifetime: region.lower_into(interner),
429 Closure(def_id, substs) => apply(
430 chalk_ir::TypeName::Closure(chalk_ir::ClosureId(def_id)),
431 substs.lower_into(interner),
433 Generator(_def_id, _substs, _) => unimplemented!(),
434 GeneratorWitness(_) => unimplemented!(),
435 Never => apply(chalk_ir::TypeName::Never, empty()),
437 apply(chalk_ir::TypeName::Tuple(substs.len()), substs.lower_into(interner))
439 Projection(proj) => TyData::Alias(proj.lower_into(interner)).intern(interner),
440 Opaque(def_id, substs) => {
441 TyData::Alias(chalk_ir::AliasTy::Opaque(chalk_ir::OpaqueTy {
442 opaque_ty_id: chalk_ir::OpaqueTyId(def_id),
443 substitution: substs.lower_into(interner),
447 // This should have been done eagerly prior to this, and all Params
448 // should have been substituted to placeholders
449 Param(_) => panic!("Lowering Param when not expected."),
450 Bound(db, bound) => TyData::BoundVar(chalk_ir::BoundVar::new(
451 chalk_ir::DebruijnIndex::new(db.as_u32()),
455 Placeholder(_placeholder) => TyData::Placeholder(chalk_ir::PlaceholderIndex {
456 ui: chalk_ir::UniverseIndex { counter: _placeholder.universe.as_usize() },
457 idx: _placeholder.name.as_usize(),
460 Infer(_infer) => unimplemented!(),
461 Error(_) => apply(chalk_ir::TypeName::Error, empty()),
466 impl<'tcx> LowerInto<'tcx, chalk_ir::Lifetime<RustInterner<'tcx>>> for Region<'tcx> {
467 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Lifetime<RustInterner<'tcx>> {
468 use rustc_middle::ty::RegionKind::*;
472 panic!("Should have already been substituted.");
474 ReLateBound(db, br) => match br {
475 ty::BoundRegion::BrAnon(var) => {
476 chalk_ir::LifetimeData::BoundVar(chalk_ir::BoundVar::new(
477 chalk_ir::DebruijnIndex::new(db.as_u32()),
482 ty::BoundRegion::BrNamed(_def_id, _name) => unimplemented!(),
483 ty::BrEnv => unimplemented!(),
485 ReFree(_) => unimplemented!(),
486 // FIXME(chalk): need to handle ReStatic
487 ReStatic => unimplemented!(),
488 ReVar(_) => unimplemented!(),
489 RePlaceholder(placeholder_region) => {
490 chalk_ir::LifetimeData::Placeholder(chalk_ir::PlaceholderIndex {
491 ui: chalk_ir::UniverseIndex { counter: placeholder_region.universe.index() },
496 ReEmpty(_) => unimplemented!(),
497 // FIXME(chalk): need to handle ReErased
498 ReErased => unimplemented!(),
503 impl<'tcx> LowerInto<'tcx, chalk_ir::GenericArg<RustInterner<'tcx>>> for GenericArg<'tcx> {
504 fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GenericArg<RustInterner<'tcx>> {
505 match self.unpack() {
506 ty::subst::GenericArgKind::Type(ty) => {
507 chalk_ir::GenericArgData::Ty(ty.lower_into(interner))
509 ty::subst::GenericArgKind::Lifetime(lifetime) => {
510 chalk_ir::GenericArgData::Lifetime(lifetime.lower_into(interner))
512 ty::subst::GenericArgKind::Const(_) => chalk_ir::GenericArgData::Ty(
513 chalk_ir::TyData::Apply(chalk_ir::ApplicationTy {
514 name: chalk_ir::TypeName::Tuple(0),
515 substitution: chalk_ir::Substitution::empty(interner),
524 // We lower into an Option here since there are some predicates which Chalk
525 // doesn't have a representation for yet (as a `WhereClause`), but are so common
526 // that we just are accepting the unsoundness for now. The `Option` will
527 // eventually be removed.
528 impl<'tcx> LowerInto<'tcx, Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>>>
529 for ty::Predicate<'tcx>
533 interner: &RustInterner<'tcx>,
534 ) -> Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>> {
536 ty::PredicateKind::Trait(predicate, _) => {
537 let (predicate, binders, _named_regions) =
538 collect_bound_vars(interner, interner.tcx, predicate);
540 Some(chalk_ir::Binders::new(
542 chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner)),
545 ty::PredicateKind::RegionOutlives(predicate) => {
546 let (predicate, binders, _named_regions) =
547 collect_bound_vars(interner, interner.tcx, predicate);
549 Some(chalk_ir::Binders::new(
551 chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives {
552 a: predicate.0.lower_into(interner),
553 b: predicate.1.lower_into(interner),
557 ty::PredicateKind::TypeOutlives(_predicate) => None,
558 ty::PredicateKind::Projection(_predicate) => None,
559 ty::PredicateKind::WellFormed(_ty) => None,
561 ty::PredicateKind::ObjectSafe(..)
562 | ty::PredicateKind::ClosureKind(..)
563 | ty::PredicateKind::Subtype(..)
564 | ty::PredicateKind::ConstEvaluatable(..)
565 | ty::PredicateKind::ConstEquate(..) => bug!("unexpected predicate {}", &self),
570 impl<'tcx> LowerInto<'tcx, chalk_ir::Binders<chalk_ir::QuantifiedWhereClauses<RustInterner<'tcx>>>>
571 for Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>
575 interner: &RustInterner<'tcx>,
576 ) -> chalk_ir::Binders<chalk_ir::QuantifiedWhereClauses<RustInterner<'tcx>>> {
577 let (predicates, binders, _named_regions) =
578 collect_bound_vars(interner, interner.tcx, &self);
579 let where_clauses = predicates.into_iter().map(|predicate| match predicate {
580 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef { def_id, substs }) => {
581 chalk_ir::Binders::new(
582 chalk_ir::VariableKinds::new(interner),
583 chalk_ir::WhereClause::Implemented(chalk_ir::TraitRef {
584 trait_id: chalk_ir::TraitId(def_id),
585 substitution: substs.lower_into(interner),
589 ty::ExistentialPredicate::Projection(_predicate) => unimplemented!(),
590 ty::ExistentialPredicate::AutoTrait(def_id) => chalk_ir::Binders::new(
591 chalk_ir::VariableKinds::new(interner),
592 chalk_ir::WhereClause::Implemented(chalk_ir::TraitRef {
593 trait_id: chalk_ir::TraitId(def_id),
594 substitution: chalk_ir::Substitution::empty(interner),
598 let value = chalk_ir::QuantifiedWhereClauses::from(interner, where_clauses);
599 chalk_ir::Binders::new(binders, value)
603 /// To collect bound vars, we have to do two passes. In the first pass, we
604 /// collect all `BoundRegion`s and `ty::Bound`s. In the second pass, we then
605 /// replace `BrNamed` into `BrAnon`. The two separate passes are important,
606 /// since we can only replace `BrNamed` with `BrAnon`s with indices *after* all
607 /// "real" `BrAnon`s.
609 /// It's important to note that because of prior substitution, we may have
610 /// late-bound regions, even outside of fn contexts, since this is the best way
611 /// to prep types for chalk lowering.
612 crate fn collect_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>>(
613 interner: &RustInterner<'tcx>,
616 ) -> (T, chalk_ir::VariableKinds<RustInterner<'tcx>>, BTreeMap<DefId, u32>) {
617 let mut bound_vars_collector = BoundVarsCollector::new();
618 ty.skip_binder().visit_with(&mut bound_vars_collector);
619 let mut parameters = bound_vars_collector.parameters;
620 let named_parameters: BTreeMap<DefId, u32> = bound_vars_collector
624 .map(|(i, def_id)| (def_id, (i + parameters.len()) as u32))
627 let mut bound_var_substitutor = NamedBoundVarSubstitutor::new(tcx, &named_parameters);
628 let new_ty = ty.skip_binder().fold_with(&mut bound_var_substitutor);
630 for var in named_parameters.values() {
631 parameters.insert(*var, chalk_ir::VariableKind::Lifetime);
634 (0..parameters.len()).for_each(|i| {
635 parameters.get(&(i as u32)).expect(&format!("Skipped bound var index `{:?}`.", i));
638 let binders = chalk_ir::VariableKinds::from(interner, parameters.into_iter().map(|(_, v)| v));
640 (new_ty, binders, named_parameters)
643 crate struct BoundVarsCollector<'tcx> {
644 binder_index: ty::DebruijnIndex,
645 crate parameters: BTreeMap<u32, chalk_ir::VariableKind<RustInterner<'tcx>>>,
646 crate named_parameters: Vec<DefId>,
649 impl<'tcx> BoundVarsCollector<'tcx> {
650 crate fn new() -> Self {
652 binder_index: ty::INNERMOST,
653 parameters: BTreeMap::new(),
654 named_parameters: vec![],
659 impl<'tcx> TypeVisitor<'tcx> for BoundVarsCollector<'tcx> {
660 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> bool {
661 self.binder_index.shift_in(1);
662 let result = t.super_visit_with(self);
663 self.binder_index.shift_out(1);
667 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
669 ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
670 match self.parameters.entry(bound_ty.var.as_u32()) {
671 Entry::Vacant(entry) => {
672 entry.insert(chalk_ir::VariableKind::Ty(chalk_ir::TyKind::General));
674 Entry::Occupied(entry) => match entry.get() {
675 chalk_ir::VariableKind::Ty(_) => {}
684 t.super_visit_with(self)
687 fn visit_region(&mut self, r: Region<'tcx>) -> bool {
689 ty::ReLateBound(index, br) if *index == self.binder_index => match br {
690 ty::BoundRegion::BrNamed(def_id, _name) => {
691 if self.named_parameters.iter().find(|d| *d == def_id).is_none() {
692 self.named_parameters.push(*def_id);
696 ty::BoundRegion::BrAnon(var) => match self.parameters.entry(*var) {
697 Entry::Vacant(entry) => {
698 entry.insert(chalk_ir::VariableKind::Lifetime);
700 Entry::Occupied(entry) => match entry.get() {
701 chalk_ir::VariableKind::Lifetime => {}
706 ty::BrEnv => unimplemented!(),
709 ty::ReEarlyBound(_re) => {
710 // FIXME(chalk): jackh726 - I think we should always have already
711 // substituted away `ReEarlyBound`s for `ReLateBound`s, but need to confirm.
718 r.super_visit_with(self)
722 /// This is used to replace `BoundRegion::BrNamed` with `BoundRegion::BrAnon`.
723 /// Note: we assume that we will always have room for more bound vars. (i.e. we
724 /// won't ever hit the `u32` limit in `BrAnon`s).
725 struct NamedBoundVarSubstitutor<'a, 'tcx> {
727 binder_index: ty::DebruijnIndex,
728 named_parameters: &'a BTreeMap<DefId, u32>,
731 impl<'a, 'tcx> NamedBoundVarSubstitutor<'a, 'tcx> {
732 fn new(tcx: TyCtxt<'tcx>, named_parameters: &'a BTreeMap<DefId, u32>) -> Self {
733 NamedBoundVarSubstitutor { tcx, binder_index: ty::INNERMOST, named_parameters }
737 impl<'a, 'tcx> TypeFolder<'tcx> for NamedBoundVarSubstitutor<'a, 'tcx> {
738 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
742 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> Binder<T> {
743 self.binder_index.shift_in(1);
744 let result = t.super_fold_with(self);
745 self.binder_index.shift_out(1);
749 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
750 t.super_fold_with(self)
753 fn fold_region(&mut self, r: Region<'tcx>) -> Region<'tcx> {
755 ty::ReLateBound(index, br) if *index == self.binder_index => match br {
756 ty::BoundRegion::BrNamed(def_id, _name) => {
757 match self.named_parameters.get(def_id) {
759 return self.tcx.mk_region(RegionKind::ReLateBound(
761 BoundRegion::BrAnon(*idx),
764 None => panic!("Missing `BrNamed`."),
767 ty::BrEnv => unimplemented!(),
768 ty::BoundRegion::BrAnon(_) => {}
773 r.super_fold_with(self)
777 /// Used to substitute `Param`s with placeholders. We do this since Chalk
778 /// have a notion of `Param`s.
779 crate struct ParamsSubstitutor<'tcx> {
781 binder_index: ty::DebruijnIndex,
782 list: Vec<rustc_middle::ty::ParamTy>,
783 crate params: rustc_data_structures::fx::FxHashMap<usize, rustc_middle::ty::ParamTy>,
784 crate named_regions: BTreeMap<DefId, u32>,
787 impl<'tcx> ParamsSubstitutor<'tcx> {
788 crate fn new(tcx: TyCtxt<'tcx>) -> Self {
791 binder_index: ty::INNERMOST,
793 params: rustc_data_structures::fx::FxHashMap::default(),
794 named_regions: BTreeMap::default(),
799 impl<'tcx> TypeFolder<'tcx> for ParamsSubstitutor<'tcx> {
800 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
804 fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: &Binder<T>) -> Binder<T> {
805 self.binder_index.shift_in(1);
806 let result = t.super_fold_with(self);
807 self.binder_index.shift_out(1);
811 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
813 // FIXME(chalk): currently we convert params to placeholders starting at
814 // index `0`. To support placeholders, we'll actually need to do a
815 // first pass to collect placeholders. Then we can insert params after.
816 ty::Placeholder(_) => unimplemented!(),
817 ty::Param(param) => match self.list.iter().position(|r| r == ¶m) {
818 Some(_idx) => self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
819 universe: ty::UniverseIndex::from_usize(0),
820 name: ty::BoundVar::from_usize(_idx),
823 self.list.push(param);
824 let idx = self.list.len() - 1;
825 self.params.insert(idx, param);
826 self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
827 universe: ty::UniverseIndex::from_usize(0),
828 name: ty::BoundVar::from_usize(idx),
833 _ => t.super_fold_with(self),
837 fn fold_region(&mut self, r: Region<'tcx>) -> Region<'tcx> {
839 // FIXME(chalk) - jackh726 - this currently isn't hit in any tests.
840 // This covers any region variables in a goal, right?
841 ty::ReEarlyBound(_re) => match self.named_regions.get(&_re.def_id) {
842 Some(idx) => self.tcx.mk_region(RegionKind::ReLateBound(
844 BoundRegion::BrAnon(*idx),
847 let idx = self.named_regions.len() as u32;
848 self.named_regions.insert(_re.def_id, idx);
849 self.tcx.mk_region(RegionKind::ReLateBound(
851 BoundRegion::BrAnon(idx),
856 _ => r.super_fold_with(self),