summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_traits
diff options
context:
space:
mode:
Diffstat (limited to 'compiler/rustc_traits')
-rw-r--r--compiler/rustc_traits/Cargo.toml20
-rw-r--r--compiler/rustc_traits/src/chalk/db.rs796
-rw-r--r--compiler/rustc_traits/src/chalk/lowering.rs1172
-rw-r--r--compiler/rustc_traits/src/chalk/mod.rs176
-rw-r--r--compiler/rustc_traits/src/dropck_outlives.rs348
-rw-r--r--compiler/rustc_traits/src/evaluate_obligation.rs34
-rw-r--r--compiler/rustc_traits/src/implied_outlives_bounds.rs172
-rw-r--r--compiler/rustc_traits/src/lib.rs32
-rw-r--r--compiler/rustc_traits/src/normalize_erasing_regions.rs73
-rw-r--r--compiler/rustc_traits/src/normalize_projection_ty.rs45
-rw-r--r--compiler/rustc_traits/src/type_op.rs283
11 files changed, 3151 insertions, 0 deletions
diff --git a/compiler/rustc_traits/Cargo.toml b/compiler/rustc_traits/Cargo.toml
new file mode 100644
index 000000000..951554c77
--- /dev/null
+++ b/compiler/rustc_traits/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+name = "rustc_traits"
+version = "0.0.0"
+edition = "2021"
+
+[dependencies]
+tracing = "0.1"
+rustc_attr = { path = "../rustc_attr" }
+rustc_middle = { path = "../rustc_middle" }
+rustc_data_structures = { path = "../rustc_data_structures" }
+rustc_hir = { path = "../rustc_hir" }
+rustc_index = { path = "../rustc_index" }
+rustc_ast = { path = "../rustc_ast" }
+rustc_span = { path = "../rustc_span" }
+chalk-ir = "0.80.0"
+chalk-engine = "0.80.0"
+chalk-solve = "0.80.0"
+smallvec = { version = "1.8.1", features = ["union", "may_dangle"] }
+rustc_infer = { path = "../rustc_infer" }
+rustc_trait_selection = { path = "../rustc_trait_selection" }
diff --git a/compiler/rustc_traits/src/chalk/db.rs b/compiler/rustc_traits/src/chalk/db.rs
new file mode 100644
index 000000000..ff5ca0cbc
--- /dev/null
+++ b/compiler/rustc_traits/src/chalk/db.rs
@@ -0,0 +1,796 @@
+//! Provides the `RustIrDatabase` implementation for `chalk-solve`
+//!
+//! The purpose of the `chalk_solve::RustIrDatabase` is to get data about
+//! specific types, such as bounds, where clauses, or fields. This file contains
+//! the minimal logic to assemble the types for `chalk-solve` by calling out to
+//! either the `TyCtxt` (for information about types) or
+//! `crate::chalk::lowering` (to lower rustc types into Chalk types).
+
+use rustc_middle::traits::ChalkRustInterner as RustInterner;
+use rustc_middle::ty::subst::{InternalSubsts, Subst, SubstsRef};
+use rustc_middle::ty::{self, AssocKind, EarlyBinder, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable};
+
+use rustc_ast::ast;
+use rustc_attr as attr;
+
+use rustc_hir::def_id::DefId;
+
+use rustc_span::symbol::sym;
+
+use std::fmt;
+use std::sync::Arc;
+
+use crate::chalk::lowering::LowerInto;
+
+pub struct RustIrDatabase<'tcx> {
+ pub(crate) interner: RustInterner<'tcx>,
+}
+
+impl fmt::Debug for RustIrDatabase<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "RustIrDatabase")
+ }
+}
+
+impl<'tcx> RustIrDatabase<'tcx> {
+ fn where_clauses_for(
+ &self,
+ def_id: DefId,
+ bound_vars: SubstsRef<'tcx>,
+ ) -> Vec<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>> {
+ let predicates = self.interner.tcx.predicates_defined_on(def_id).predicates;
+ predicates
+ .iter()
+ .map(|(wc, _)| EarlyBinder(*wc).subst(self.interner.tcx, bound_vars))
+ .filter_map(|wc| LowerInto::<
+ Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>>
+ >::lower_into(wc, self.interner)).collect()
+ }
+
+ fn bounds_for<T>(&self, def_id: DefId, bound_vars: SubstsRef<'tcx>) -> Vec<T>
+ where
+ ty::Predicate<'tcx>: LowerInto<'tcx, std::option::Option<T>>,
+ {
+ let bounds = self.interner.tcx.bound_explicit_item_bounds(def_id);
+ bounds
+ .0
+ .iter()
+ .map(|(bound, _)| bounds.rebind(*bound).subst(self.interner.tcx, &bound_vars))
+ .filter_map(|bound| LowerInto::<Option<_>>::lower_into(bound, self.interner))
+ .collect()
+ }
+}
+
+impl<'tcx> chalk_solve::RustIrDatabase<RustInterner<'tcx>> for RustIrDatabase<'tcx> {
+ fn interner(&self) -> RustInterner<'tcx> {
+ self.interner
+ }
+
+ fn associated_ty_data(
+ &self,
+ assoc_type_id: chalk_ir::AssocTypeId<RustInterner<'tcx>>,
+ ) -> Arc<chalk_solve::rust_ir::AssociatedTyDatum<RustInterner<'tcx>>> {
+ let def_id = assoc_type_id.0;
+ let assoc_item = self.interner.tcx.associated_item(def_id);
+ let Some(trait_def_id) = assoc_item.trait_container(self.interner.tcx) else {
+ unimplemented!("Not possible??");
+ };
+ match assoc_item.kind {
+ AssocKind::Type => {}
+ _ => unimplemented!("Not possible??"),
+ }
+ let bound_vars = bound_vars_for_item(self.interner.tcx, def_id);
+ let binders = binders_for(self.interner, bound_vars);
+
+ let where_clauses = self.where_clauses_for(def_id, bound_vars);
+ let bounds = self.bounds_for(def_id, bound_vars);
+
+ Arc::new(chalk_solve::rust_ir::AssociatedTyDatum {
+ trait_id: chalk_ir::TraitId(trait_def_id),
+ id: assoc_type_id,
+ name: (),
+ binders: chalk_ir::Binders::new(
+ binders,
+ chalk_solve::rust_ir::AssociatedTyDatumBound { bounds, where_clauses },
+ ),
+ })
+ }
+
+ fn trait_datum(
+ &self,
+ trait_id: chalk_ir::TraitId<RustInterner<'tcx>>,
+ ) -> Arc<chalk_solve::rust_ir::TraitDatum<RustInterner<'tcx>>> {
+ use chalk_solve::rust_ir::WellKnownTrait::*;
+
+ let def_id = trait_id.0;
+ let trait_def = self.interner.tcx.trait_def(def_id);
+
+ let bound_vars = bound_vars_for_item(self.interner.tcx, def_id);
+ let binders = binders_for(self.interner, bound_vars);
+
+ let where_clauses = self.where_clauses_for(def_id, bound_vars);
+
+ let associated_ty_ids: Vec<_> = self
+ .interner
+ .tcx
+ .associated_items(def_id)
+ .in_definition_order()
+ .filter(|i| i.kind == AssocKind::Type)
+ .map(|i| chalk_ir::AssocTypeId(i.def_id))
+ .collect();
+
+ let lang_items = self.interner.tcx.lang_items();
+ let well_known = if lang_items.sized_trait() == Some(def_id) {
+ Some(Sized)
+ } else if lang_items.copy_trait() == Some(def_id) {
+ Some(Copy)
+ } else if lang_items.clone_trait() == Some(def_id) {
+ Some(Clone)
+ } else if lang_items.drop_trait() == Some(def_id) {
+ Some(Drop)
+ } else if lang_items.fn_trait() == Some(def_id) {
+ Some(Fn)
+ } else if lang_items.fn_once_trait() == Some(def_id) {
+ Some(FnOnce)
+ } else if lang_items.fn_mut_trait() == Some(def_id) {
+ Some(FnMut)
+ } else if lang_items.unsize_trait() == Some(def_id) {
+ Some(Unsize)
+ } else if lang_items.unpin_trait() == Some(def_id) {
+ Some(Unpin)
+ } else if lang_items.coerce_unsized_trait() == Some(def_id) {
+ Some(CoerceUnsized)
+ } else if lang_items.dispatch_from_dyn_trait() == Some(def_id) {
+ Some(DispatchFromDyn)
+ } else {
+ None
+ };
+ Arc::new(chalk_solve::rust_ir::TraitDatum {
+ id: trait_id,
+ binders: chalk_ir::Binders::new(
+ binders,
+ chalk_solve::rust_ir::TraitDatumBound { where_clauses },
+ ),
+ flags: chalk_solve::rust_ir::TraitFlags {
+ auto: trait_def.has_auto_impl,
+ marker: trait_def.is_marker,
+ upstream: !def_id.is_local(),
+ fundamental: self.interner.tcx.has_attr(def_id, sym::fundamental),
+ non_enumerable: true,
+ coinductive: false,
+ },
+ associated_ty_ids,
+ well_known,
+ })
+ }
+
+ fn adt_datum(
+ &self,
+ adt_id: chalk_ir::AdtId<RustInterner<'tcx>>,
+ ) -> Arc<chalk_solve::rust_ir::AdtDatum<RustInterner<'tcx>>> {
+ let adt_def = adt_id.0;
+
+ let bound_vars = bound_vars_for_item(self.interner.tcx, adt_def.did());
+ let binders = binders_for(self.interner, bound_vars);
+
+ let where_clauses = self.where_clauses_for(adt_def.did(), bound_vars);
+
+ let variants: Vec<_> = adt_def
+ .variants()
+ .iter()
+ .map(|variant| chalk_solve::rust_ir::AdtVariantDatum {
+ fields: variant
+ .fields
+ .iter()
+ .map(|field| field.ty(self.interner.tcx, bound_vars).lower_into(self.interner))
+ .collect(),
+ })
+ .collect();
+ Arc::new(chalk_solve::rust_ir::AdtDatum {
+ id: adt_id,
+ binders: chalk_ir::Binders::new(
+ binders,
+ chalk_solve::rust_ir::AdtDatumBound { variants, where_clauses },
+ ),
+ flags: chalk_solve::rust_ir::AdtFlags {
+ upstream: !adt_def.did().is_local(),
+ fundamental: adt_def.is_fundamental(),
+ phantom_data: adt_def.is_phantom_data(),
+ },
+ kind: match adt_def.adt_kind() {
+ ty::AdtKind::Struct => chalk_solve::rust_ir::AdtKind::Struct,
+ ty::AdtKind::Union => chalk_solve::rust_ir::AdtKind::Union,
+ ty::AdtKind::Enum => chalk_solve::rust_ir::AdtKind::Enum,
+ },
+ })
+ }
+
+ fn adt_repr(
+ &self,
+ adt_id: chalk_ir::AdtId<RustInterner<'tcx>>,
+ ) -> Arc<chalk_solve::rust_ir::AdtRepr<RustInterner<'tcx>>> {
+ let adt_def = adt_id.0;
+ let int = |i| chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Int(i)).intern(self.interner);
+ let uint = |i| chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(i)).intern(self.interner);
+ Arc::new(chalk_solve::rust_ir::AdtRepr {
+ c: adt_def.repr().c(),
+ packed: adt_def.repr().packed(),
+ int: adt_def.repr().int.map(|i| match i {
+ attr::IntType::SignedInt(ty) => match ty {
+ ast::IntTy::Isize => int(chalk_ir::IntTy::Isize),
+ ast::IntTy::I8 => int(chalk_ir::IntTy::I8),
+ ast::IntTy::I16 => int(chalk_ir::IntTy::I16),
+ ast::IntTy::I32 => int(chalk_ir::IntTy::I32),
+ ast::IntTy::I64 => int(chalk_ir::IntTy::I64),
+ ast::IntTy::I128 => int(chalk_ir::IntTy::I128),
+ },
+ attr::IntType::UnsignedInt(ty) => match ty {
+ ast::UintTy::Usize => uint(chalk_ir::UintTy::Usize),
+ ast::UintTy::U8 => uint(chalk_ir::UintTy::U8),
+ ast::UintTy::U16 => uint(chalk_ir::UintTy::U16),
+ ast::UintTy::U32 => uint(chalk_ir::UintTy::U32),
+ ast::UintTy::U64 => uint(chalk_ir::UintTy::U64),
+ ast::UintTy::U128 => uint(chalk_ir::UintTy::U128),
+ },
+ }),
+ })
+ }
+
+ fn adt_size_align(
+ &self,
+ adt_id: chalk_ir::AdtId<RustInterner<'tcx>>,
+ ) -> Arc<chalk_solve::rust_ir::AdtSizeAlign> {
+ let tcx = self.interner.tcx;
+ let did = adt_id.0.did();
+
+ // Grab the ADT and the param we might need to calculate its layout
+ let param_env = tcx.param_env(did);
+ let adt_ty = tcx.type_of(did);
+
+ // The ADT is a 1-zst if it's a ZST and its alignment is 1.
+ // Mark the ADT as _not_ a 1-zst if there was a layout error.
+ let one_zst = if let Ok(layout) = tcx.layout_of(param_env.and(adt_ty)) {
+ layout.is_zst() && layout.align.abi.bytes() == 1
+ } else {
+ false
+ };
+
+ Arc::new(chalk_solve::rust_ir::AdtSizeAlign::from_one_zst(one_zst))
+ }
+
+ fn fn_def_datum(
+ &self,
+ fn_def_id: chalk_ir::FnDefId<RustInterner<'tcx>>,
+ ) -> Arc<chalk_solve::rust_ir::FnDefDatum<RustInterner<'tcx>>> {
+ let def_id = fn_def_id.0;
+ let bound_vars = bound_vars_for_item(self.interner.tcx, def_id);
+ let binders = binders_for(self.interner, bound_vars);
+
+ let where_clauses = self.where_clauses_for(def_id, bound_vars);
+
+ let sig = self.interner.tcx.bound_fn_sig(def_id);
+ let (inputs_and_output, iobinders, _) = crate::chalk::lowering::collect_bound_vars(
+ self.interner,
+ self.interner.tcx,
+ sig.map_bound(|s| s.inputs_and_output()).subst(self.interner.tcx, bound_vars),
+ );
+
+ let argument_types = inputs_and_output[..inputs_and_output.len() - 1]
+ .iter()
+ .map(|t| sig.rebind(*t).subst(self.interner.tcx, &bound_vars).lower_into(self.interner))
+ .collect();
+
+ let return_type = sig
+ .rebind(inputs_and_output[inputs_and_output.len() - 1])
+ .subst(self.interner.tcx, &bound_vars)
+ .lower_into(self.interner);
+
+ let bound = chalk_solve::rust_ir::FnDefDatumBound {
+ inputs_and_output: chalk_ir::Binders::new(
+ iobinders,
+ chalk_solve::rust_ir::FnDefInputsAndOutputDatum { argument_types, return_type },
+ ),
+ where_clauses,
+ };
+ Arc::new(chalk_solve::rust_ir::FnDefDatum {
+ id: fn_def_id,
+ sig: sig.0.lower_into(self.interner),
+ binders: chalk_ir::Binders::new(binders, bound),
+ })
+ }
+
+ fn impl_datum(
+ &self,
+ impl_id: chalk_ir::ImplId<RustInterner<'tcx>>,
+ ) -> Arc<chalk_solve::rust_ir::ImplDatum<RustInterner<'tcx>>> {
+ let def_id = impl_id.0;
+ let bound_vars = bound_vars_for_item(self.interner.tcx, def_id);
+ let binders = binders_for(self.interner, bound_vars);
+
+ let trait_ref = self.interner.tcx.bound_impl_trait_ref(def_id).expect("not an impl");
+ let trait_ref = trait_ref.subst(self.interner.tcx, bound_vars);
+
+ let where_clauses = self.where_clauses_for(def_id, bound_vars);
+
+ let value = chalk_solve::rust_ir::ImplDatumBound {
+ trait_ref: trait_ref.lower_into(self.interner),
+ where_clauses,
+ };
+
+ let associated_ty_value_ids: Vec<_> = self
+ .interner
+ .tcx
+ .associated_items(def_id)
+ .in_definition_order()
+ .filter(|i| i.kind == AssocKind::Type)
+ .map(|i| chalk_solve::rust_ir::AssociatedTyValueId(i.def_id))
+ .collect();
+
+ Arc::new(chalk_solve::rust_ir::ImplDatum {
+ polarity: self.interner.tcx.impl_polarity(def_id).lower_into(self.interner),
+ binders: chalk_ir::Binders::new(binders, value),
+ impl_type: chalk_solve::rust_ir::ImplType::Local,
+ associated_ty_value_ids,
+ })
+ }
+
+ fn impls_for_trait(
+ &self,
+ trait_id: chalk_ir::TraitId<RustInterner<'tcx>>,
+ parameters: &[chalk_ir::GenericArg<RustInterner<'tcx>>],
+ _binders: &chalk_ir::CanonicalVarKinds<RustInterner<'tcx>>,
+ ) -> Vec<chalk_ir::ImplId<RustInterner<'tcx>>> {
+ let def_id = trait_id.0;
+
+ // FIXME(chalk): use TraitDef::for_each_relevant_impl, but that will
+ // require us to be able to interconvert `Ty<'tcx>`, and we're
+ // not there yet.
+
+ let all_impls = self.interner.tcx.all_impls(def_id);
+ let matched_impls = all_impls.filter(|impl_def_id| {
+ use chalk_ir::could_match::CouldMatch;
+ let trait_ref = self.interner.tcx.bound_impl_trait_ref(*impl_def_id).unwrap();
+ let bound_vars = bound_vars_for_item(self.interner.tcx, *impl_def_id);
+
+ let self_ty = trait_ref.map_bound(|t| t.self_ty());
+ let self_ty = self_ty.subst(self.interner.tcx, bound_vars);
+ let lowered_ty = self_ty.lower_into(self.interner);
+
+ parameters[0].assert_ty_ref(self.interner).could_match(
+ self.interner,
+ self.unification_database(),
+ &lowered_ty,
+ )
+ });
+
+ let impls = matched_impls.map(chalk_ir::ImplId).collect();
+ impls
+ }
+
+ fn impl_provided_for(
+ &self,
+ auto_trait_id: chalk_ir::TraitId<RustInterner<'tcx>>,
+ chalk_ty: &chalk_ir::TyKind<RustInterner<'tcx>>,
+ ) -> bool {
+ use chalk_ir::Scalar::*;
+ use chalk_ir::TyKind::*;
+
+ let trait_def_id = auto_trait_id.0;
+ let all_impls = self.interner.tcx.all_impls(trait_def_id);
+ for impl_def_id in all_impls {
+ let trait_ref = self.interner.tcx.impl_trait_ref(impl_def_id).unwrap();
+ let self_ty = trait_ref.self_ty();
+ let provides = match (self_ty.kind(), chalk_ty) {
+ (&ty::Adt(impl_adt_def, ..), Adt(id, ..)) => impl_adt_def.did() == id.0.did(),
+ (_, AssociatedType(_ty_id, ..)) => {
+ // FIXME(chalk): See https://github.com/rust-lang/rust/pull/77152#discussion_r494484774
+ false
+ }
+ (ty::Bool, Scalar(Bool)) => true,
+ (ty::Char, Scalar(Char)) => true,
+ (ty::Int(ty1), Scalar(Int(ty2))) => matches!(
+ (ty1, ty2),
+ (ty::IntTy::Isize, chalk_ir::IntTy::Isize)
+ | (ty::IntTy::I8, chalk_ir::IntTy::I8)
+ | (ty::IntTy::I16, chalk_ir::IntTy::I16)
+ | (ty::IntTy::I32, chalk_ir::IntTy::I32)
+ | (ty::IntTy::I64, chalk_ir::IntTy::I64)
+ | (ty::IntTy::I128, chalk_ir::IntTy::I128)
+ ),
+ (ty::Uint(ty1), Scalar(Uint(ty2))) => matches!(
+ (ty1, ty2),
+ (ty::UintTy::Usize, chalk_ir::UintTy::Usize)
+ | (ty::UintTy::U8, chalk_ir::UintTy::U8)
+ | (ty::UintTy::U16, chalk_ir::UintTy::U16)
+ | (ty::UintTy::U32, chalk_ir::UintTy::U32)
+ | (ty::UintTy::U64, chalk_ir::UintTy::U64)
+ | (ty::UintTy::U128, chalk_ir::UintTy::U128)
+ ),
+ (ty::Float(ty1), Scalar(Float(ty2))) => matches!(
+ (ty1, ty2),
+ (ty::FloatTy::F32, chalk_ir::FloatTy::F32)
+ | (ty::FloatTy::F64, chalk_ir::FloatTy::F64)
+ ),
+ (&ty::Tuple(substs), Tuple(len, _)) => substs.len() == *len,
+ (&ty::Array(..), Array(..)) => true,
+ (&ty::Slice(..), Slice(..)) => true,
+ (&ty::RawPtr(type_and_mut), Raw(mutability, _)) => {
+ match (type_and_mut.mutbl, mutability) {
+ (ast::Mutability::Mut, chalk_ir::Mutability::Mut) => true,
+ (ast::Mutability::Mut, chalk_ir::Mutability::Not) => false,
+ (ast::Mutability::Not, chalk_ir::Mutability::Mut) => false,
+ (ast::Mutability::Not, chalk_ir::Mutability::Not) => true,
+ }
+ }
+ (&ty::Ref(.., mutability1), Ref(mutability2, ..)) => {
+ match (mutability1, mutability2) {
+ (ast::Mutability::Mut, chalk_ir::Mutability::Mut) => true,
+ (ast::Mutability::Mut, chalk_ir::Mutability::Not) => false,
+ (ast::Mutability::Not, chalk_ir::Mutability::Mut) => false,
+ (ast::Mutability::Not, chalk_ir::Mutability::Not) => true,
+ }
+ }
+ (&ty::Opaque(def_id, ..), OpaqueType(opaque_ty_id, ..)) => def_id == opaque_ty_id.0,
+ (&ty::FnDef(def_id, ..), FnDef(fn_def_id, ..)) => def_id == fn_def_id.0,
+ (&ty::Str, Str) => true,
+ (&ty::Never, Never) => true,
+ (&ty::Closure(def_id, ..), Closure(closure_id, _)) => def_id == closure_id.0,
+ (&ty::Foreign(def_id), Foreign(foreign_def_id)) => def_id == foreign_def_id.0,
+ (&ty::Error(..), Error) => false,
+ _ => false,
+ };
+ if provides {
+ return true;
+ }
+ }
+ false
+ }
+
+ fn associated_ty_value(
+ &self,
+ associated_ty_id: chalk_solve::rust_ir::AssociatedTyValueId<RustInterner<'tcx>>,
+ ) -> Arc<chalk_solve::rust_ir::AssociatedTyValue<RustInterner<'tcx>>> {
+ let def_id = associated_ty_id.0;
+ let assoc_item = self.interner.tcx.associated_item(def_id);
+ let impl_id = assoc_item.container_id(self.interner.tcx);
+ match assoc_item.kind {
+ AssocKind::Type => {}
+ _ => unimplemented!("Not possible??"),
+ }
+
+ let trait_item_id = assoc_item.trait_item_def_id.expect("assoc_ty with no trait version");
+ let bound_vars = bound_vars_for_item(self.interner.tcx, def_id);
+ let binders = binders_for(self.interner, bound_vars);
+ let ty = self
+ .interner
+ .tcx
+ .bound_type_of(def_id)
+ .subst(self.interner.tcx, bound_vars)
+ .lower_into(self.interner);
+
+ Arc::new(chalk_solve::rust_ir::AssociatedTyValue {
+ impl_id: chalk_ir::ImplId(impl_id),
+ associated_ty_id: chalk_ir::AssocTypeId(trait_item_id),
+ value: chalk_ir::Binders::new(
+ binders,
+ chalk_solve::rust_ir::AssociatedTyValueBound { ty },
+ ),
+ })
+ }
+
+ fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<RustInterner<'tcx>>> {
+ vec![]
+ }
+
+ fn local_impls_to_coherence_check(
+ &self,
+ _trait_id: chalk_ir::TraitId<RustInterner<'tcx>>,
+ ) -> Vec<chalk_ir::ImplId<RustInterner<'tcx>>> {
+ unimplemented!()
+ }
+
+ fn opaque_ty_data(
+ &self,
+ opaque_ty_id: chalk_ir::OpaqueTyId<RustInterner<'tcx>>,
+ ) -> Arc<chalk_solve::rust_ir::OpaqueTyDatum<RustInterner<'tcx>>> {
+ let bound_vars = ty::fold::shift_vars(
+ self.interner.tcx,
+ bound_vars_for_item(self.interner.tcx, opaque_ty_id.0),
+ 1,
+ );
+ let where_clauses = self.where_clauses_for(opaque_ty_id.0, bound_vars);
+
+ let identity_substs = InternalSubsts::identity_for_item(self.interner.tcx, opaque_ty_id.0);
+
+ let explicit_item_bounds = self.interner.tcx.bound_explicit_item_bounds(opaque_ty_id.0);
+ let bounds =
+ explicit_item_bounds
+ .0
+ .iter()
+ .map(|(bound, _)| {
+ explicit_item_bounds.rebind(*bound).subst(self.interner.tcx, &bound_vars)
+ })
+ .map(|bound| {
+ bound.fold_with(&mut ReplaceOpaqueTyFolder {
+ tcx: self.interner.tcx,
+ opaque_ty_id,
+ identity_substs,
+ binder_index: ty::INNERMOST,
+ })
+ })
+ .filter_map(|bound| {
+ LowerInto::<
+ Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>>
+ >::lower_into(bound, self.interner)
+ })
+ .collect();
+
+ // Binder for the bound variable representing the concrete impl Trait type.
+ let existential_binder = chalk_ir::VariableKinds::from1(
+ self.interner,
+ chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
+ );
+
+ let value = chalk_solve::rust_ir::OpaqueTyDatumBound {
+ bounds: chalk_ir::Binders::new(existential_binder.clone(), bounds),
+ where_clauses: chalk_ir::Binders::new(existential_binder, where_clauses),
+ };
+
+ let binders = binders_for(self.interner, bound_vars);
+ Arc::new(chalk_solve::rust_ir::OpaqueTyDatum {
+ opaque_ty_id,
+ bound: chalk_ir::Binders::new(binders, value),
+ })
+ }
+
+ fn program_clauses_for_env(
+ &self,
+ environment: &chalk_ir::Environment<RustInterner<'tcx>>,
+ ) -> chalk_ir::ProgramClauses<RustInterner<'tcx>> {
+ chalk_solve::program_clauses_for_env(self, environment)
+ }
+
+ fn well_known_trait_id(
+ &self,
+ well_known_trait: chalk_solve::rust_ir::WellKnownTrait,
+ ) -> Option<chalk_ir::TraitId<RustInterner<'tcx>>> {
+ use chalk_solve::rust_ir::WellKnownTrait::*;
+ let lang_items = self.interner.tcx.lang_items();
+ let def_id = match well_known_trait {
+ Sized => lang_items.sized_trait(),
+ Copy => lang_items.copy_trait(),
+ Clone => lang_items.clone_trait(),
+ Drop => lang_items.drop_trait(),
+ Fn => lang_items.fn_trait(),
+ FnMut => lang_items.fn_mut_trait(),
+ FnOnce => lang_items.fn_once_trait(),
+ Generator => lang_items.gen_trait(),
+ Unsize => lang_items.unsize_trait(),
+ Unpin => lang_items.unpin_trait(),
+ CoerceUnsized => lang_items.coerce_unsized_trait(),
+ DiscriminantKind => lang_items.discriminant_kind_trait(),
+ DispatchFromDyn => lang_items.dispatch_from_dyn_trait(),
+ };
+ def_id.map(chalk_ir::TraitId)
+ }
+
+ fn is_object_safe(&self, trait_id: chalk_ir::TraitId<RustInterner<'tcx>>) -> bool {
+ self.interner.tcx.is_object_safe(trait_id.0)
+ }
+
+ fn hidden_opaque_type(
+ &self,
+ _id: chalk_ir::OpaqueTyId<RustInterner<'tcx>>,
+ ) -> chalk_ir::Ty<RustInterner<'tcx>> {
+ // FIXME(chalk): actually get hidden ty
+ self.interner
+ .tcx
+ .mk_ty(ty::Tuple(self.interner.tcx.intern_type_list(&[])))
+ .lower_into(self.interner)
+ }
+
+ fn closure_kind(
+ &self,
+ _closure_id: chalk_ir::ClosureId<RustInterner<'tcx>>,
+ substs: &chalk_ir::Substitution<RustInterner<'tcx>>,
+ ) -> chalk_solve::rust_ir::ClosureKind {
+ let kind = &substs.as_slice(self.interner)[substs.len(self.interner) - 3];
+ match kind.assert_ty_ref(self.interner).kind(self.interner) {
+ chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Int(int_ty)) => match int_ty {
+ chalk_ir::IntTy::I8 => chalk_solve::rust_ir::ClosureKind::Fn,
+ chalk_ir::IntTy::I16 => chalk_solve::rust_ir::ClosureKind::FnMut,
+ chalk_ir::IntTy::I32 => chalk_solve::rust_ir::ClosureKind::FnOnce,
+ _ => bug!("bad closure kind"),
+ },
+ _ => bug!("bad closure kind"),
+ }
+ }
+
+ fn closure_inputs_and_output(
+ &self,
+ _closure_id: chalk_ir::ClosureId<RustInterner<'tcx>>,
+ substs: &chalk_ir::Substitution<RustInterner<'tcx>>,
+ ) -> chalk_ir::Binders<chalk_solve::rust_ir::FnDefInputsAndOutputDatum<RustInterner<'tcx>>>
+ {
+ let sig = &substs.as_slice(self.interner)[substs.len(self.interner) - 2];
+ match sig.assert_ty_ref(self.interner).kind(self.interner) {
+ chalk_ir::TyKind::Function(f) => {
+ let substitution = f.substitution.0.as_slice(self.interner);
+ let return_type = substitution.last().unwrap().assert_ty_ref(self.interner).clone();
+ // Closure arguments are tupled
+ let argument_tuple = substitution[0].assert_ty_ref(self.interner);
+ let argument_types = match argument_tuple.kind(self.interner) {
+ chalk_ir::TyKind::Tuple(_len, substitution) => substitution
+ .iter(self.interner)
+ .map(|arg| arg.assert_ty_ref(self.interner))
+ .cloned()
+ .collect(),
+ _ => bug!("Expecting closure FnSig args to be tupled."),
+ };
+
+ chalk_ir::Binders::new(
+ chalk_ir::VariableKinds::from_iter(
+ self.interner,
+ (0..f.num_binders).map(|_| chalk_ir::VariableKind::Lifetime),
+ ),
+ chalk_solve::rust_ir::FnDefInputsAndOutputDatum { argument_types, return_type },
+ )
+ }
+ _ => panic!("Invalid sig."),
+ }
+ }
+
+ fn closure_upvars(
+ &self,
+ _closure_id: chalk_ir::ClosureId<RustInterner<'tcx>>,
+ substs: &chalk_ir::Substitution<RustInterner<'tcx>>,
+ ) -> chalk_ir::Binders<chalk_ir::Ty<RustInterner<'tcx>>> {
+ let inputs_and_output = self.closure_inputs_and_output(_closure_id, substs);
+ let tuple = substs.as_slice(self.interner).last().unwrap().assert_ty_ref(self.interner);
+ inputs_and_output.map_ref(|_| tuple.clone())
+ }
+
+ fn closure_fn_substitution(
+ &self,
+ _closure_id: chalk_ir::ClosureId<RustInterner<'tcx>>,
+ substs: &chalk_ir::Substitution<RustInterner<'tcx>>,
+ ) -> chalk_ir::Substitution<RustInterner<'tcx>> {
+ let substitution = &substs.as_slice(self.interner)[0..substs.len(self.interner) - 3];
+ chalk_ir::Substitution::from_iter(self.interner, substitution)
+ }
+
+ fn generator_datum(
+ &self,
+ _generator_id: chalk_ir::GeneratorId<RustInterner<'tcx>>,
+ ) -> Arc<chalk_solve::rust_ir::GeneratorDatum<RustInterner<'tcx>>> {
+ unimplemented!()
+ }
+
+ fn generator_witness_datum(
+ &self,
+ _generator_id: chalk_ir::GeneratorId<RustInterner<'tcx>>,
+ ) -> Arc<chalk_solve::rust_ir::GeneratorWitnessDatum<RustInterner<'tcx>>> {
+ unimplemented!()
+ }
+
+ fn unification_database(&self) -> &dyn chalk_ir::UnificationDatabase<RustInterner<'tcx>> {
+ self
+ }
+
+ fn discriminant_type(
+ &self,
+ _: chalk_ir::Ty<RustInterner<'tcx>>,
+ ) -> chalk_ir::Ty<RustInterner<'tcx>> {
+ unimplemented!()
+ }
+}
+
+impl<'tcx> chalk_ir::UnificationDatabase<RustInterner<'tcx>> for RustIrDatabase<'tcx> {
+ fn fn_def_variance(
+ &self,
+ def_id: chalk_ir::FnDefId<RustInterner<'tcx>>,
+ ) -> chalk_ir::Variances<RustInterner<'tcx>> {
+ let variances = self.interner.tcx.variances_of(def_id.0);
+ chalk_ir::Variances::from_iter(
+ self.interner,
+ variances.iter().map(|v| v.lower_into(self.interner)),
+ )
+ }
+
+ fn adt_variance(
+ &self,
+ adt_id: chalk_ir::AdtId<RustInterner<'tcx>>,
+ ) -> chalk_ir::Variances<RustInterner<'tcx>> {
+ let variances = self.interner.tcx.variances_of(adt_id.0.did());
+ chalk_ir::Variances::from_iter(
+ self.interner,
+ variances.iter().map(|v| v.lower_into(self.interner)),
+ )
+ }
+}
+
+/// Creates an `InternalSubsts` that maps each generic parameter to a higher-ranked
+/// var bound at index `0`. For types, we use a `BoundVar` index equal to
+/// the type parameter index. For regions, we use the `BoundRegionKind::BrNamed`
+/// variant (which has a `DefId`).
+fn bound_vars_for_item<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> {
+ InternalSubsts::for_item(tcx, def_id, |param, substs| match param.kind {
+ ty::GenericParamDefKind::Type { .. } => tcx
+ .mk_ty(ty::Bound(
+ ty::INNERMOST,
+ ty::BoundTy {
+ var: ty::BoundVar::from(param.index),
+ kind: ty::BoundTyKind::Param(param.name),
+ },
+ ))
+ .into(),
+
+ ty::GenericParamDefKind::Lifetime => {
+ let br = ty::BoundRegion {
+ var: ty::BoundVar::from_usize(substs.len()),
+ kind: ty::BrAnon(substs.len() as u32),
+ };
+ tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)).into()
+ }
+
+ ty::GenericParamDefKind::Const { .. } => tcx
+ .mk_const(ty::ConstS {
+ kind: ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from(param.index)),
+ ty: tcx.type_of(param.def_id),
+ })
+ .into(),
+ })
+}
+
+fn binders_for<'tcx>(
+ interner: RustInterner<'tcx>,
+ bound_vars: SubstsRef<'tcx>,
+) -> chalk_ir::VariableKinds<RustInterner<'tcx>> {
+ chalk_ir::VariableKinds::from_iter(
+ interner,
+ bound_vars.iter().map(|arg| match arg.unpack() {
+ ty::subst::GenericArgKind::Lifetime(_re) => chalk_ir::VariableKind::Lifetime,
+ ty::subst::GenericArgKind::Type(_ty) => {
+ chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General)
+ }
+ ty::subst::GenericArgKind::Const(c) => {
+ chalk_ir::VariableKind::Const(c.ty().lower_into(interner))
+ }
+ }),
+ )
+}
+
+struct ReplaceOpaqueTyFolder<'tcx> {
+ tcx: TyCtxt<'tcx>,
+ opaque_ty_id: chalk_ir::OpaqueTyId<RustInterner<'tcx>>,
+ identity_substs: SubstsRef<'tcx>,
+ binder_index: ty::DebruijnIndex,
+}
+
+impl<'tcx> ty::TypeFolder<'tcx> for ReplaceOpaqueTyFolder<'tcx> {
+ fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
+ self.tcx
+ }
+
+ fn fold_binder<T: TypeFoldable<'tcx>>(
+ &mut self,
+ t: ty::Binder<'tcx, T>,
+ ) -> ty::Binder<'tcx, T> {
+ self.binder_index.shift_in(1);
+ let t = t.super_fold_with(self);
+ self.binder_index.shift_out(1);
+ t
+ }
+
+ fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
+ if let ty::Opaque(def_id, substs) = *ty.kind() {
+ if def_id == self.opaque_ty_id.0 && substs == self.identity_substs {
+ return self.tcx.mk_ty(ty::Bound(
+ self.binder_index,
+ ty::BoundTy::from(ty::BoundVar::from_u32(0)),
+ ));
+ }
+ }
+ ty
+ }
+}
diff --git a/compiler/rustc_traits/src/chalk/lowering.rs b/compiler/rustc_traits/src/chalk/lowering.rs
new file mode 100644
index 000000000..c7c604e14
--- /dev/null
+++ b/compiler/rustc_traits/src/chalk/lowering.rs
@@ -0,0 +1,1172 @@
+//! Contains the logic to lower rustc types into Chalk types
+//!
+//! In many cases there is a 1:1 relationship between a rustc type and a Chalk type.
+//! For example, a `SubstsRef` maps almost directly to a `Substitution`. In some
+//! other cases, such as `Param`s, there is no Chalk type, so we have to handle
+//! accordingly.
+//!
+//! ## `Ty` lowering
+//! Much of the `Ty` lowering is 1:1 with Chalk. (Or will be eventually). A
+//! helpful table for what types lower to what can be found in the
+//! [Chalk book](https://rust-lang.github.io/chalk/book/types/rust_types.html).
+//! The most notable difference lies with `Param`s. To convert from rustc to
+//! Chalk, we eagerly and deeply convert `Param`s to placeholders (in goals) or
+//! bound variables (for clause generation through functions in `db`).
+//!
+//! ## `Region` lowering
+//! Regions are handled in rustc and Chalk is quite differently. In rustc, there
+//! is a difference between "early bound" and "late bound" regions, where only
+//! the late bound regions have a `DebruijnIndex`. Moreover, in Chalk all
+//! regions (Lifetimes) have an associated index. In rustc, only `BrAnon`s have
+//! an index, whereas `BrNamed` don't. In order to lower regions to Chalk, we
+//! convert all regions into `BrAnon` late-bound regions.
+//!
+//! ## `Const` lowering
+//! Chalk doesn't handle consts currently, so consts are currently lowered to
+//! an empty tuple.
+//!
+//! ## Bound variable collection
+//! Another difference between rustc and Chalk lies in the handling of binders.
+//! Chalk requires that we store the bound parameter kinds, whereas rustc does
+//! not. To lower anything wrapped in a `Binder`, we first deeply find any bound
+//! variables from the current `Binder`.
+
+use rustc_ast::ast;
+use rustc_middle::traits::{ChalkEnvironmentAndGoal, ChalkRustInterner as RustInterner};
+use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
+use rustc_middle::ty::{
+ self, Binder, Region, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
+ TypeSuperVisitable, TypeVisitable, TypeVisitor,
+};
+use rustc_span::def_id::DefId;
+
+use chalk_ir::{FnSig, ForeignDefId};
+use rustc_hir::Unsafety;
+use std::collections::btree_map::{BTreeMap, Entry};
+use std::ops::ControlFlow;
+
+/// Essentially an `Into` with a `&RustInterner` parameter
+pub(crate) trait LowerInto<'tcx, T> {
+ /// Lower a rustc construct (e.g., `ty::TraitPredicate`) to a chalk type, consuming `self`.
+ fn lower_into(self, interner: RustInterner<'tcx>) -> T;
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::Substitution<RustInterner<'tcx>>> for SubstsRef<'tcx> {
+ fn lower_into(
+ self,
+ interner: RustInterner<'tcx>,
+ ) -> chalk_ir::Substitution<RustInterner<'tcx>> {
+ chalk_ir::Substitution::from_iter(interner, self.iter().map(|s| s.lower_into(interner)))
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, SubstsRef<'tcx>> for &chalk_ir::Substitution<RustInterner<'tcx>> {
+ fn lower_into(self, interner: RustInterner<'tcx>) -> SubstsRef<'tcx> {
+ interner.tcx.mk_substs(self.iter(interner).map(|subst| subst.lower_into(interner)))
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::AliasTy<RustInterner<'tcx>>> for ty::ProjectionTy<'tcx> {
+ fn lower_into(self, interner: RustInterner<'tcx>) -> chalk_ir::AliasTy<RustInterner<'tcx>> {
+ chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy {
+ associated_ty_id: chalk_ir::AssocTypeId(self.item_def_id),
+ substitution: self.substs.lower_into(interner),
+ })
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment<chalk_ir::Goal<RustInterner<'tcx>>>>
+ for ChalkEnvironmentAndGoal<'tcx>
+{
+ fn lower_into(
+ self,
+ interner: RustInterner<'tcx>,
+ ) -> chalk_ir::InEnvironment<chalk_ir::Goal<RustInterner<'tcx>>> {
+ let clauses = self.environment.into_iter().map(|predicate| {
+ let (predicate, binders, _named_regions) =
+ collect_bound_vars(interner, interner.tcx, predicate.kind());
+ let consequence = match predicate {
+ ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
+ chalk_ir::DomainGoal::FromEnv(chalk_ir::FromEnv::Ty(ty.lower_into(interner)))
+ }
+ ty::PredicateKind::Trait(predicate) => chalk_ir::DomainGoal::FromEnv(
+ chalk_ir::FromEnv::Trait(predicate.trait_ref.lower_into(interner)),
+ ),
+ ty::PredicateKind::RegionOutlives(predicate) => chalk_ir::DomainGoal::Holds(
+ chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives {
+ a: predicate.0.lower_into(interner),
+ b: predicate.1.lower_into(interner),
+ }),
+ ),
+ ty::PredicateKind::TypeOutlives(predicate) => chalk_ir::DomainGoal::Holds(
+ chalk_ir::WhereClause::TypeOutlives(chalk_ir::TypeOutlives {
+ ty: predicate.0.lower_into(interner),
+ lifetime: predicate.1.lower_into(interner),
+ }),
+ ),
+ ty::PredicateKind::Projection(predicate) => chalk_ir::DomainGoal::Holds(
+ chalk_ir::WhereClause::AliasEq(predicate.lower_into(interner)),
+ ),
+ ty::PredicateKind::WellFormed(arg) => match arg.unpack() {
+ ty::GenericArgKind::Type(ty) => chalk_ir::DomainGoal::WellFormed(
+ chalk_ir::WellFormed::Ty(ty.lower_into(interner)),
+ ),
+ // FIXME(chalk): we need to change `WellFormed` in Chalk to take a `GenericArg`
+ _ => chalk_ir::DomainGoal::WellFormed(chalk_ir::WellFormed::Ty(
+ interner.tcx.types.unit.lower_into(interner),
+ )),
+ },
+ ty::PredicateKind::ObjectSafe(..)
+ | ty::PredicateKind::ClosureKind(..)
+ | ty::PredicateKind::Subtype(..)
+ | ty::PredicateKind::Coerce(..)
+ | ty::PredicateKind::ConstEvaluatable(..)
+ | ty::PredicateKind::ConstEquate(..) => bug!("unexpected predicate {}", predicate),
+ };
+ let value = chalk_ir::ProgramClauseImplication {
+ consequence,
+ conditions: chalk_ir::Goals::empty(interner),
+ priority: chalk_ir::ClausePriority::High,
+ constraints: chalk_ir::Constraints::empty(interner),
+ };
+ chalk_ir::ProgramClauseData(chalk_ir::Binders::new(binders, value)).intern(interner)
+ });
+
+ let goal: chalk_ir::GoalData<RustInterner<'tcx>> = self.goal.lower_into(interner);
+ chalk_ir::InEnvironment {
+ environment: chalk_ir::Environment {
+ clauses: chalk_ir::ProgramClauses::from_iter(interner, clauses),
+ },
+ goal: goal.intern(interner),
+ }
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData<RustInterner<'tcx>>> for ty::Predicate<'tcx> {
+ fn lower_into(self, interner: RustInterner<'tcx>) -> chalk_ir::GoalData<RustInterner<'tcx>> {
+ let (predicate, binders, _named_regions) =
+ collect_bound_vars(interner, interner.tcx, self.kind());
+
+ let value = match predicate {
+ ty::PredicateKind::Trait(predicate) => {
+ chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
+ chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner)),
+ ))
+ }
+ ty::PredicateKind::RegionOutlives(predicate) => {
+ chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
+ chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives {
+ a: predicate.0.lower_into(interner),
+ b: predicate.1.lower_into(interner),
+ }),
+ ))
+ }
+ ty::PredicateKind::TypeOutlives(predicate) => {
+ chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
+ chalk_ir::WhereClause::TypeOutlives(chalk_ir::TypeOutlives {
+ ty: predicate.0.lower_into(interner),
+ lifetime: predicate.1.lower_into(interner),
+ }),
+ ))
+ }
+ ty::PredicateKind::Projection(predicate) => {
+ chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds(
+ chalk_ir::WhereClause::AliasEq(predicate.lower_into(interner)),
+ ))
+ }
+ ty::PredicateKind::WellFormed(arg) => match arg.unpack() {
+ GenericArgKind::Type(ty) => match ty.kind() {
+ // FIXME(chalk): In Chalk, a placeholder is WellFormed if it
+ // `FromEnv`. However, when we "lower" Params, we don't update
+ // the environment.
+ ty::Placeholder(..) => {
+ chalk_ir::GoalData::All(chalk_ir::Goals::empty(interner))
+ }
+
+ _ => chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::WellFormed(
+ chalk_ir::WellFormed::Ty(ty.lower_into(interner)),
+ )),
+ },
+ // FIXME(chalk): handle well formed consts
+ GenericArgKind::Const(..) => {
+ chalk_ir::GoalData::All(chalk_ir::Goals::empty(interner))
+ }
+ GenericArgKind::Lifetime(lt) => bug!("unexpect well formed predicate: {:?}", lt),
+ },
+
+ ty::PredicateKind::ObjectSafe(t) => chalk_ir::GoalData::DomainGoal(
+ chalk_ir::DomainGoal::ObjectSafe(chalk_ir::TraitId(t)),
+ ),
+
+ ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => {
+ chalk_ir::GoalData::SubtypeGoal(chalk_ir::SubtypeGoal {
+ a: a.lower_into(interner),
+ b: b.lower_into(interner),
+ })
+ }
+
+ // FIXME(chalk): other predicates
+ //
+ // We can defer this, but ultimately we'll want to express
+ // some of these in terms of chalk operations.
+ ty::PredicateKind::ClosureKind(..)
+ | ty::PredicateKind::Coerce(..)
+ | ty::PredicateKind::ConstEvaluatable(..)
+ | ty::PredicateKind::ConstEquate(..) => {
+ chalk_ir::GoalData::All(chalk_ir::Goals::empty(interner))
+ }
+ ty::PredicateKind::TypeWellFormedFromEnv(ty) => chalk_ir::GoalData::DomainGoal(
+ chalk_ir::DomainGoal::FromEnv(chalk_ir::FromEnv::Ty(ty.lower_into(interner))),
+ ),
+ };
+
+ chalk_ir::GoalData::Quantified(
+ chalk_ir::QuantifierKind::ForAll,
+ chalk_ir::Binders::new(binders, value.intern(interner)),
+ )
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::TraitRef<RustInterner<'tcx>>>
+ for rustc_middle::ty::TraitRef<'tcx>
+{
+ fn lower_into(self, interner: RustInterner<'tcx>) -> chalk_ir::TraitRef<RustInterner<'tcx>> {
+ chalk_ir::TraitRef {
+ trait_id: chalk_ir::TraitId(self.def_id),
+ substitution: self.substs.lower_into(interner),
+ }
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::AliasEq<RustInterner<'tcx>>>
+ for rustc_middle::ty::ProjectionPredicate<'tcx>
+{
+ fn lower_into(self, interner: RustInterner<'tcx>) -> chalk_ir::AliasEq<RustInterner<'tcx>> {
+ // FIXME(associated_const_equality): teach chalk about terms for alias eq.
+ chalk_ir::AliasEq {
+ ty: self.term.ty().unwrap().lower_into(interner),
+ alias: self.projection_ty.lower_into(interner),
+ }
+ }
+}
+
+/*
+// FIXME(...): Where do I add this to Chalk? I can't find it in the rustc repo anywhere.
+impl<'tcx> LowerInto<'tcx, chalk_ir::Term<RustInterner<'tcx>>> for rustc_middle::ty::Term<'tcx> {
+ fn lower_into(self, interner: RustInterner<'tcx>) -> chalk_ir::Term<RustInterner<'tcx>> {
+ match self {
+ ty::Term::Ty(ty) => ty.lower_into(interner).into(),
+ ty::Term::Const(c) => c.lower_into(interner).into(),
+ }
+ }
+}
+*/
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::Ty<RustInterner<'tcx>>> for Ty<'tcx> {
+ fn lower_into(self, interner: RustInterner<'tcx>) -> chalk_ir::Ty<RustInterner<'tcx>> {
+ let int = |i| chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Int(i));
+ let uint = |i| chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(i));
+ let float = |f| chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Float(f));
+
+ match *self.kind() {
+ ty::Bool => chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Bool),
+ ty::Char => chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Char),
+ ty::Int(ty) => match ty {
+ ty::IntTy::Isize => int(chalk_ir::IntTy::Isize),
+ ty::IntTy::I8 => int(chalk_ir::IntTy::I8),
+ ty::IntTy::I16 => int(chalk_ir::IntTy::I16),
+ ty::IntTy::I32 => int(chalk_ir::IntTy::I32),
+ ty::IntTy::I64 => int(chalk_ir::IntTy::I64),
+ ty::IntTy::I128 => int(chalk_ir::IntTy::I128),
+ },
+ ty::Uint(ty) => match ty {
+ ty::UintTy::Usize => uint(chalk_ir::UintTy::Usize),
+ ty::UintTy::U8 => uint(chalk_ir::UintTy::U8),
+ ty::UintTy::U16 => uint(chalk_ir::UintTy::U16),
+ ty::UintTy::U32 => uint(chalk_ir::UintTy::U32),
+ ty::UintTy::U64 => uint(chalk_ir::UintTy::U64),
+ ty::UintTy::U128 => uint(chalk_ir::UintTy::U128),
+ },
+ ty::Float(ty) => match ty {
+ ty::FloatTy::F32 => float(chalk_ir::FloatTy::F32),
+ ty::FloatTy::F64 => float(chalk_ir::FloatTy::F64),
+ },
+ ty::Adt(def, substs) => {
+ chalk_ir::TyKind::Adt(chalk_ir::AdtId(def), substs.lower_into(interner))
+ }
+ ty::Foreign(def_id) => chalk_ir::TyKind::Foreign(ForeignDefId(def_id)),
+ ty::Str => chalk_ir::TyKind::Str,
+ ty::Array(ty, len) => {
+ chalk_ir::TyKind::Array(ty.lower_into(interner), len.lower_into(interner))
+ }
+ ty::Slice(ty) => chalk_ir::TyKind::Slice(ty.lower_into(interner)),
+
+ ty::RawPtr(ptr) => {
+ chalk_ir::TyKind::Raw(ptr.mutbl.lower_into(interner), ptr.ty.lower_into(interner))
+ }
+ ty::Ref(region, ty, mutability) => chalk_ir::TyKind::Ref(
+ mutability.lower_into(interner),
+ region.lower_into(interner),
+ ty.lower_into(interner),
+ ),
+ ty::FnDef(def_id, substs) => {
+ chalk_ir::TyKind::FnDef(chalk_ir::FnDefId(def_id), substs.lower_into(interner))
+ }
+ ty::FnPtr(sig) => {
+ let (inputs_and_outputs, binders, _named_regions) =
+ collect_bound_vars(interner, interner.tcx, sig.inputs_and_output());
+ chalk_ir::TyKind::Function(chalk_ir::FnPointer {
+ num_binders: binders.len(interner),
+ sig: sig.lower_into(interner),
+ substitution: chalk_ir::FnSubst(chalk_ir::Substitution::from_iter(
+ interner,
+ inputs_and_outputs.iter().map(|ty| {
+ chalk_ir::GenericArgData::Ty(ty.lower_into(interner)).intern(interner)
+ }),
+ )),
+ })
+ }
+ ty::Dynamic(predicates, region) => chalk_ir::TyKind::Dyn(chalk_ir::DynTy {
+ bounds: predicates.lower_into(interner),
+ lifetime: region.lower_into(interner),
+ }),
+ ty::Closure(def_id, substs) => {
+ chalk_ir::TyKind::Closure(chalk_ir::ClosureId(def_id), substs.lower_into(interner))
+ }
+ ty::Generator(def_id, substs, _) => chalk_ir::TyKind::Generator(
+ chalk_ir::GeneratorId(def_id),
+ substs.lower_into(interner),
+ ),
+ ty::GeneratorWitness(_) => unimplemented!(),
+ ty::Never => chalk_ir::TyKind::Never,
+ ty::Tuple(types) => {
+ chalk_ir::TyKind::Tuple(types.len(), types.as_substs().lower_into(interner))
+ }
+ ty::Projection(proj) => chalk_ir::TyKind::Alias(proj.lower_into(interner)),
+ ty::Opaque(def_id, substs) => {
+ chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Opaque(chalk_ir::OpaqueTy {
+ opaque_ty_id: chalk_ir::OpaqueTyId(def_id),
+ substitution: substs.lower_into(interner),
+ }))
+ }
+ // This should have been done eagerly prior to this, and all Params
+ // should have been substituted to placeholders
+ ty::Param(_) => panic!("Lowering Param when not expected."),
+ ty::Bound(db, bound) => chalk_ir::TyKind::BoundVar(chalk_ir::BoundVar::new(
+ chalk_ir::DebruijnIndex::new(db.as_u32()),
+ bound.var.index(),
+ )),
+ ty::Placeholder(_placeholder) => {
+ chalk_ir::TyKind::Placeholder(chalk_ir::PlaceholderIndex {
+ ui: chalk_ir::UniverseIndex { counter: _placeholder.universe.as_usize() },
+ idx: _placeholder.name.as_usize(),
+ })
+ }
+ ty::Infer(_infer) => unimplemented!(),
+ ty::Error(_) => chalk_ir::TyKind::Error,
+ }
+ .intern(interner)
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, Ty<'tcx>> for &chalk_ir::Ty<RustInterner<'tcx>> {
+ fn lower_into(self, interner: RustInterner<'tcx>) -> Ty<'tcx> {
+ use chalk_ir::TyKind;
+
+ let kind = match self.kind(interner) {
+ TyKind::Adt(struct_id, substitution) => {
+ ty::Adt(struct_id.0, substitution.lower_into(interner))
+ }
+ TyKind::Scalar(scalar) => match scalar {
+ chalk_ir::Scalar::Bool => ty::Bool,
+ chalk_ir::Scalar::Char => ty::Char,
+ chalk_ir::Scalar::Int(int_ty) => match int_ty {
+ chalk_ir::IntTy::Isize => ty::Int(ty::IntTy::Isize),
+ chalk_ir::IntTy::I8 => ty::Int(ty::IntTy::I8),
+ chalk_ir::IntTy::I16 => ty::Int(ty::IntTy::I16),
+ chalk_ir::IntTy::I32 => ty::Int(ty::IntTy::I32),
+ chalk_ir::IntTy::I64 => ty::Int(ty::IntTy::I64),
+ chalk_ir::IntTy::I128 => ty::Int(ty::IntTy::I128),
+ },
+ chalk_ir::Scalar::Uint(int_ty) => match int_ty {
+ chalk_ir::UintTy::Usize => ty::Uint(ty::UintTy::Usize),
+ chalk_ir::UintTy::U8 => ty::Uint(ty::UintTy::U8),
+ chalk_ir::UintTy::U16 => ty::Uint(ty::UintTy::U16),
+ chalk_ir::UintTy::U32 => ty::Uint(ty::UintTy::U32),
+ chalk_ir::UintTy::U64 => ty::Uint(ty::UintTy::U64),
+ chalk_ir::UintTy::U128 => ty::Uint(ty::UintTy::U128),
+ },
+ chalk_ir::Scalar::Float(float_ty) => match float_ty {
+ chalk_ir::FloatTy::F32 => ty::Float(ty::FloatTy::F32),
+ chalk_ir::FloatTy::F64 => ty::Float(ty::FloatTy::F64),
+ },
+ },
+ TyKind::Array(ty, c) => {
+ let ty = ty.lower_into(interner);
+ let c = c.lower_into(interner);
+ ty::Array(ty, c)
+ }
+ TyKind::FnDef(id, substitution) => ty::FnDef(id.0, substitution.lower_into(interner)),
+ TyKind::Closure(closure, substitution) => {
+ ty::Closure(closure.0, substitution.lower_into(interner))
+ }
+ TyKind::Generator(..) => unimplemented!(),
+ TyKind::GeneratorWitness(..) => unimplemented!(),
+ TyKind::Never => ty::Never,
+ TyKind::Tuple(_len, substitution) => {
+ ty::Tuple(substitution.lower_into(interner).try_as_type_list().unwrap())
+ }
+ TyKind::Slice(ty) => ty::Slice(ty.lower_into(interner)),
+ TyKind::Raw(mutbl, ty) => ty::RawPtr(ty::TypeAndMut {
+ ty: ty.lower_into(interner),
+ mutbl: mutbl.lower_into(interner),
+ }),
+ TyKind::Ref(mutbl, lifetime, ty) => ty::Ref(
+ lifetime.lower_into(interner),
+ ty.lower_into(interner),
+ mutbl.lower_into(interner),
+ ),
+ TyKind::Str => ty::Str,
+ TyKind::OpaqueType(opaque_ty, substitution) => {
+ ty::Opaque(opaque_ty.0, substitution.lower_into(interner))
+ }
+ TyKind::AssociatedType(assoc_ty, substitution) => ty::Projection(ty::ProjectionTy {
+ substs: substitution.lower_into(interner),
+ item_def_id: assoc_ty.0,
+ }),
+ TyKind::Foreign(def_id) => ty::Foreign(def_id.0),
+ TyKind::Error => return interner.tcx.ty_error(),
+ TyKind::Placeholder(placeholder) => ty::Placeholder(ty::Placeholder {
+ universe: ty::UniverseIndex::from_usize(placeholder.ui.counter),
+ name: ty::BoundVar::from_usize(placeholder.idx),
+ }),
+ TyKind::Alias(alias_ty) => match alias_ty {
+ chalk_ir::AliasTy::Projection(projection) => ty::Projection(ty::ProjectionTy {
+ item_def_id: projection.associated_ty_id.0,
+ substs: projection.substitution.lower_into(interner),
+ }),
+ chalk_ir::AliasTy::Opaque(opaque) => {
+ ty::Opaque(opaque.opaque_ty_id.0, opaque.substitution.lower_into(interner))
+ }
+ },
+ TyKind::Function(_quantified_ty) => unimplemented!(),
+ TyKind::BoundVar(_bound) => ty::Bound(
+ ty::DebruijnIndex::from_usize(_bound.debruijn.depth() as usize),
+ ty::BoundTy {
+ var: ty::BoundVar::from_usize(_bound.index),
+ kind: ty::BoundTyKind::Anon,
+ },
+ ),
+ TyKind::InferenceVar(_, _) => unimplemented!(),
+ TyKind::Dyn(_) => unimplemented!(),
+ };
+ interner.tcx.mk_ty(kind)
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::Lifetime<RustInterner<'tcx>>> for Region<'tcx> {
+ fn lower_into(self, interner: RustInterner<'tcx>) -> chalk_ir::Lifetime<RustInterner<'tcx>> {
+ match *self {
+ ty::ReEarlyBound(_) => {
+ panic!("Should have already been substituted.");
+ }
+ ty::ReLateBound(db, br) => chalk_ir::LifetimeData::BoundVar(chalk_ir::BoundVar::new(
+ chalk_ir::DebruijnIndex::new(db.as_u32()),
+ br.var.as_usize(),
+ ))
+ .intern(interner),
+ ty::ReFree(_) => unimplemented!(),
+ ty::ReStatic => chalk_ir::LifetimeData::Static.intern(interner),
+ ty::ReVar(_) => unimplemented!(),
+ ty::RePlaceholder(placeholder_region) => {
+ chalk_ir::LifetimeData::Placeholder(chalk_ir::PlaceholderIndex {
+ ui: chalk_ir::UniverseIndex { counter: placeholder_region.universe.index() },
+ idx: 0,
+ })
+ .intern(interner)
+ }
+ ty::ReEmpty(ui) => {
+ chalk_ir::LifetimeData::Empty(chalk_ir::UniverseIndex { counter: ui.index() })
+ .intern(interner)
+ }
+ ty::ReErased => chalk_ir::LifetimeData::Erased.intern(interner),
+ }
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, Region<'tcx>> for &chalk_ir::Lifetime<RustInterner<'tcx>> {
+ fn lower_into(self, interner: RustInterner<'tcx>) -> Region<'tcx> {
+ let kind = match self.data(interner) {
+ chalk_ir::LifetimeData::BoundVar(var) => ty::ReLateBound(
+ ty::DebruijnIndex::from_u32(var.debruijn.depth()),
+ ty::BoundRegion {
+ var: ty::BoundVar::from_usize(var.index),
+ kind: ty::BrAnon(var.index as u32),
+ },
+ ),
+ chalk_ir::LifetimeData::InferenceVar(_var) => unimplemented!(),
+ chalk_ir::LifetimeData::Placeholder(p) => ty::RePlaceholder(ty::Placeholder {
+ universe: ty::UniverseIndex::from_usize(p.ui.counter),
+ name: ty::BoundRegionKind::BrAnon(p.idx as u32),
+ }),
+ chalk_ir::LifetimeData::Static => return interner.tcx.lifetimes.re_static,
+ chalk_ir::LifetimeData::Empty(ui) => {
+ ty::ReEmpty(ty::UniverseIndex::from_usize(ui.counter))
+ }
+ chalk_ir::LifetimeData::Erased => return interner.tcx.lifetimes.re_erased,
+ chalk_ir::LifetimeData::Phantom(void, _) => match *void {},
+ };
+ interner.tcx.mk_region(kind)
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::Const<RustInterner<'tcx>>> for ty::Const<'tcx> {
+ fn lower_into(self, interner: RustInterner<'tcx>) -> chalk_ir::Const<RustInterner<'tcx>> {
+ let ty = self.ty().lower_into(interner);
+ let value = match self.kind() {
+ ty::ConstKind::Value(val) => {
+ chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: val })
+ }
+ ty::ConstKind::Bound(db, bound) => chalk_ir::ConstValue::BoundVar(
+ chalk_ir::BoundVar::new(chalk_ir::DebruijnIndex::new(db.as_u32()), bound.index()),
+ ),
+ _ => unimplemented!("Const not implemented. {:?}", self),
+ };
+ chalk_ir::ConstData { ty, value }.intern(interner)
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, ty::Const<'tcx>> for &chalk_ir::Const<RustInterner<'tcx>> {
+ fn lower_into(self, interner: RustInterner<'tcx>) -> ty::Const<'tcx> {
+ let data = self.data(interner);
+ let ty = data.ty.lower_into(interner);
+ let kind = match data.value {
+ chalk_ir::ConstValue::BoundVar(var) => ty::ConstKind::Bound(
+ ty::DebruijnIndex::from_u32(var.debruijn.depth()),
+ ty::BoundVar::from_u32(var.index as u32),
+ ),
+ chalk_ir::ConstValue::InferenceVar(_var) => unimplemented!(),
+ chalk_ir::ConstValue::Placeholder(_p) => unimplemented!(),
+ chalk_ir::ConstValue::Concrete(c) => ty::ConstKind::Value(c.interned),
+ };
+ interner.tcx.mk_const(ty::ConstS { ty, kind })
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::GenericArg<RustInterner<'tcx>>> for GenericArg<'tcx> {
+ fn lower_into(self, interner: RustInterner<'tcx>) -> chalk_ir::GenericArg<RustInterner<'tcx>> {
+ match self.unpack() {
+ ty::subst::GenericArgKind::Type(ty) => {
+ chalk_ir::GenericArgData::Ty(ty.lower_into(interner))
+ }
+ ty::subst::GenericArgKind::Lifetime(lifetime) => {
+ chalk_ir::GenericArgData::Lifetime(lifetime.lower_into(interner))
+ }
+ ty::subst::GenericArgKind::Const(c) => {
+ chalk_ir::GenericArgData::Const(c.lower_into(interner))
+ }
+ }
+ .intern(interner)
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, ty::subst::GenericArg<'tcx>>
+ for &chalk_ir::GenericArg<RustInterner<'tcx>>
+{
+ fn lower_into(self, interner: RustInterner<'tcx>) -> ty::subst::GenericArg<'tcx> {
+ match self.data(interner) {
+ chalk_ir::GenericArgData::Ty(ty) => {
+ let t: Ty<'tcx> = ty.lower_into(interner);
+ t.into()
+ }
+ chalk_ir::GenericArgData::Lifetime(lifetime) => {
+ let r: Region<'tcx> = lifetime.lower_into(interner);
+ r.into()
+ }
+ chalk_ir::GenericArgData::Const(c) => {
+ let c: ty::Const<'tcx> = c.lower_into(interner);
+ c.into()
+ }
+ }
+ }
+}
+
+// We lower into an Option here since there are some predicates which Chalk
+// doesn't have a representation for yet (as a `WhereClause`), but are so common
+// that we just are accepting the unsoundness for now. The `Option` will
+// eventually be removed.
+impl<'tcx> LowerInto<'tcx, Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>>>
+ for ty::Predicate<'tcx>
+{
+ fn lower_into(
+ self,
+ interner: RustInterner<'tcx>,
+ ) -> Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>> {
+ let (predicate, binders, _named_regions) =
+ collect_bound_vars(interner, interner.tcx, self.kind());
+ let value = match predicate {
+ ty::PredicateKind::Trait(predicate) => {
+ Some(chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner)))
+ }
+ ty::PredicateKind::RegionOutlives(predicate) => {
+ Some(chalk_ir::WhereClause::LifetimeOutlives(chalk_ir::LifetimeOutlives {
+ a: predicate.0.lower_into(interner),
+ b: predicate.1.lower_into(interner),
+ }))
+ }
+ ty::PredicateKind::TypeOutlives(predicate) => {
+ Some(chalk_ir::WhereClause::TypeOutlives(chalk_ir::TypeOutlives {
+ ty: predicate.0.lower_into(interner),
+ lifetime: predicate.1.lower_into(interner),
+ }))
+ }
+ ty::PredicateKind::Projection(predicate) => {
+ Some(chalk_ir::WhereClause::AliasEq(predicate.lower_into(interner)))
+ }
+ ty::PredicateKind::WellFormed(_ty) => None,
+
+ ty::PredicateKind::ObjectSafe(..)
+ | ty::PredicateKind::ClosureKind(..)
+ | ty::PredicateKind::Subtype(..)
+ | ty::PredicateKind::Coerce(..)
+ | ty::PredicateKind::ConstEvaluatable(..)
+ | ty::PredicateKind::ConstEquate(..)
+ | ty::PredicateKind::TypeWellFormedFromEnv(..) => {
+ bug!("unexpected predicate {}", &self)
+ }
+ };
+ value.map(|value| chalk_ir::Binders::new(binders, value))
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::Binders<chalk_ir::QuantifiedWhereClauses<RustInterner<'tcx>>>>
+ for &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>
+{
+ fn lower_into(
+ self,
+ interner: RustInterner<'tcx>,
+ ) -> chalk_ir::Binders<chalk_ir::QuantifiedWhereClauses<RustInterner<'tcx>>> {
+ // `Self` has one binder:
+ // Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>
+ // The return type has two:
+ // Binders<&[Binders<WhereClause<I>>]>
+ // This means that any variables that are escaping `self` need to be
+ // shifted in by one so that they are still escaping.
+ let predicates = ty::fold::shift_vars(interner.tcx, self, 1);
+
+ let self_ty = interner.tcx.mk_ty(ty::Bound(
+ // This is going to be wrapped in a binder
+ ty::DebruijnIndex::from_usize(1),
+ ty::BoundTy { var: ty::BoundVar::from_usize(0), kind: ty::BoundTyKind::Anon },
+ ));
+ let where_clauses = predicates.into_iter().map(|predicate| {
+ let (predicate, binders, _named_regions) =
+ collect_bound_vars(interner, interner.tcx, predicate);
+ match predicate {
+ ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef { def_id, substs }) => {
+ chalk_ir::Binders::new(
+ binders.clone(),
+ chalk_ir::WhereClause::Implemented(chalk_ir::TraitRef {
+ trait_id: chalk_ir::TraitId(def_id),
+ substitution: interner
+ .tcx
+ .mk_substs_trait(self_ty, substs)
+ .lower_into(interner),
+ }),
+ )
+ }
+ ty::ExistentialPredicate::Projection(predicate) => chalk_ir::Binders::new(
+ binders.clone(),
+ chalk_ir::WhereClause::AliasEq(chalk_ir::AliasEq {
+ alias: chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy {
+ associated_ty_id: chalk_ir::AssocTypeId(predicate.item_def_id),
+ substitution: interner
+ .tcx
+ .mk_substs_trait(self_ty, predicate.substs)
+ .lower_into(interner),
+ }),
+ // FIXME(associated_const_equality): teach chalk about terms for alias eq.
+ ty: predicate.term.ty().unwrap().lower_into(interner),
+ }),
+ ),
+ ty::ExistentialPredicate::AutoTrait(def_id) => chalk_ir::Binders::new(
+ binders.clone(),
+ chalk_ir::WhereClause::Implemented(chalk_ir::TraitRef {
+ trait_id: chalk_ir::TraitId(def_id),
+ substitution: interner
+ .tcx
+ .mk_substs_trait(self_ty, &[])
+ .lower_into(interner),
+ }),
+ ),
+ }
+ });
+
+ // Binder for the bound variable representing the concrete underlying type.
+ let existential_binder = chalk_ir::VariableKinds::from1(
+ interner,
+ chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
+ );
+ let value = chalk_ir::QuantifiedWhereClauses::from_iter(interner, where_clauses);
+ chalk_ir::Binders::new(existential_binder, value)
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::FnSig<RustInterner<'tcx>>>
+ for ty::Binder<'tcx, ty::FnSig<'tcx>>
+{
+ fn lower_into(self, _interner: RustInterner<'_>) -> FnSig<RustInterner<'tcx>> {
+ chalk_ir::FnSig {
+ abi: self.abi(),
+ safety: match self.unsafety() {
+ Unsafety::Normal => chalk_ir::Safety::Safe,
+ Unsafety::Unsafe => chalk_ir::Safety::Unsafe,
+ },
+ variadic: self.c_variadic(),
+ }
+ }
+}
+
+// We lower into an Option here since there are some predicates which Chalk
+// doesn't have a representation for yet (as an `InlineBound`). The `Option` will
+// eventually be removed.
+impl<'tcx> LowerInto<'tcx, Option<chalk_solve::rust_ir::QuantifiedInlineBound<RustInterner<'tcx>>>>
+ for ty::Predicate<'tcx>
+{
+ fn lower_into(
+ self,
+ interner: RustInterner<'tcx>,
+ ) -> Option<chalk_solve::rust_ir::QuantifiedInlineBound<RustInterner<'tcx>>> {
+ let (predicate, binders, _named_regions) =
+ collect_bound_vars(interner, interner.tcx, self.kind());
+ match predicate {
+ ty::PredicateKind::Trait(predicate) => Some(chalk_ir::Binders::new(
+ binders,
+ chalk_solve::rust_ir::InlineBound::TraitBound(
+ predicate.trait_ref.lower_into(interner),
+ ),
+ )),
+ ty::PredicateKind::Projection(predicate) => Some(chalk_ir::Binders::new(
+ binders,
+ chalk_solve::rust_ir::InlineBound::AliasEqBound(predicate.lower_into(interner)),
+ )),
+ ty::PredicateKind::TypeOutlives(_predicate) => None,
+ ty::PredicateKind::WellFormed(_ty) => None,
+
+ ty::PredicateKind::RegionOutlives(..)
+ | ty::PredicateKind::ObjectSafe(..)
+ | ty::PredicateKind::ClosureKind(..)
+ | ty::PredicateKind::Subtype(..)
+ | ty::PredicateKind::Coerce(..)
+ | ty::PredicateKind::ConstEvaluatable(..)
+ | ty::PredicateKind::ConstEquate(..)
+ | ty::PredicateKind::TypeWellFormedFromEnv(..) => {
+ bug!("unexpected predicate {}", &self)
+ }
+ }
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_solve::rust_ir::TraitBound<RustInterner<'tcx>>>
+ for ty::TraitRef<'tcx>
+{
+ fn lower_into(
+ self,
+ interner: RustInterner<'tcx>,
+ ) -> chalk_solve::rust_ir::TraitBound<RustInterner<'tcx>> {
+ chalk_solve::rust_ir::TraitBound {
+ trait_id: chalk_ir::TraitId(self.def_id),
+ args_no_self: self.substs[1..].iter().map(|arg| arg.lower_into(interner)).collect(),
+ }
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_ir::Mutability> for ast::Mutability {
+ fn lower_into(self, _interner: RustInterner<'tcx>) -> chalk_ir::Mutability {
+ match self {
+ rustc_ast::Mutability::Mut => chalk_ir::Mutability::Mut,
+ rustc_ast::Mutability::Not => chalk_ir::Mutability::Not,
+ }
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, ast::Mutability> for chalk_ir::Mutability {
+ fn lower_into(self, _interner: RustInterner<'tcx>) -> ast::Mutability {
+ match self {
+ chalk_ir::Mutability::Mut => ast::Mutability::Mut,
+ chalk_ir::Mutability::Not => ast::Mutability::Not,
+ }
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_solve::rust_ir::Polarity> for ty::ImplPolarity {
+ fn lower_into(self, _interner: RustInterner<'tcx>) -> chalk_solve::rust_ir::Polarity {
+ match self {
+ ty::ImplPolarity::Positive => chalk_solve::rust_ir::Polarity::Positive,
+ ty::ImplPolarity::Negative => chalk_solve::rust_ir::Polarity::Negative,
+ // FIXME(chalk) reservation impls
+ ty::ImplPolarity::Reservation => chalk_solve::rust_ir::Polarity::Negative,
+ }
+ }
+}
+impl<'tcx> LowerInto<'tcx, chalk_ir::Variance> for ty::Variance {
+ fn lower_into(self, _interner: RustInterner<'tcx>) -> chalk_ir::Variance {
+ match self {
+ ty::Variance::Covariant => chalk_ir::Variance::Covariant,
+ ty::Variance::Invariant => chalk_ir::Variance::Invariant,
+ ty::Variance::Contravariant => chalk_ir::Variance::Contravariant,
+ ty::Variance::Bivariant => unimplemented!(),
+ }
+ }
+}
+
+impl<'tcx> LowerInto<'tcx, chalk_solve::rust_ir::AliasEqBound<RustInterner<'tcx>>>
+ for ty::ProjectionPredicate<'tcx>
+{
+ fn lower_into(
+ self,
+ interner: RustInterner<'tcx>,
+ ) -> chalk_solve::rust_ir::AliasEqBound<RustInterner<'tcx>> {
+ let (trait_ref, own_substs) = self.projection_ty.trait_ref_and_own_substs(interner.tcx);
+ chalk_solve::rust_ir::AliasEqBound {
+ trait_bound: trait_ref.lower_into(interner),
+ associated_ty_id: chalk_ir::AssocTypeId(self.projection_ty.item_def_id),
+ parameters: own_substs.iter().map(|arg| arg.lower_into(interner)).collect(),
+ value: self.term.ty().unwrap().lower_into(interner),
+ }
+ }
+}
+
+/// To collect bound vars, we have to do two passes. In the first pass, we
+/// collect all `BoundRegionKind`s and `ty::Bound`s. In the second pass, we then
+/// replace `BrNamed` into `BrAnon`. The two separate passes are important,
+/// since we can only replace `BrNamed` with `BrAnon`s with indices *after* all
+/// "real" `BrAnon`s.
+///
+/// It's important to note that because of prior substitution, we may have
+/// late-bound regions, even outside of fn contexts, since this is the best way
+/// to prep types for chalk lowering.
+pub(crate) fn collect_bound_vars<'tcx, T: TypeFoldable<'tcx>>(
+ interner: RustInterner<'tcx>,
+ tcx: TyCtxt<'tcx>,
+ ty: Binder<'tcx, T>,
+) -> (T, chalk_ir::VariableKinds<RustInterner<'tcx>>, BTreeMap<DefId, u32>) {
+ let mut bound_vars_collector = BoundVarsCollector::new();
+ ty.as_ref().skip_binder().visit_with(&mut bound_vars_collector);
+ let mut parameters = bound_vars_collector.parameters;
+ let named_parameters: BTreeMap<DefId, u32> = bound_vars_collector
+ .named_parameters
+ .into_iter()
+ .enumerate()
+ .map(|(i, def_id)| (def_id, (i + parameters.len()) as u32))
+ .collect();
+
+ let mut bound_var_substitutor = NamedBoundVarSubstitutor::new(tcx, &named_parameters);
+ let new_ty = ty.skip_binder().fold_with(&mut bound_var_substitutor);
+
+ for var in named_parameters.values() {
+ parameters.insert(*var, chalk_ir::VariableKind::Lifetime);
+ }
+
+ (0..parameters.len()).for_each(|i| {
+ parameters
+ .get(&(i as u32))
+ .or_else(|| bug!("Skipped bound var index: parameters={:?}", parameters));
+ });
+
+ let binders =
+ chalk_ir::VariableKinds::from_iter(interner, parameters.into_iter().map(|(_, v)| v));
+
+ (new_ty, binders, named_parameters)
+}
+
+pub(crate) struct BoundVarsCollector<'tcx> {
+ binder_index: ty::DebruijnIndex,
+ pub(crate) parameters: BTreeMap<u32, chalk_ir::VariableKind<RustInterner<'tcx>>>,
+ pub(crate) named_parameters: Vec<DefId>,
+}
+
+impl<'tcx> BoundVarsCollector<'tcx> {
+ pub(crate) fn new() -> Self {
+ BoundVarsCollector {
+ binder_index: ty::INNERMOST,
+ parameters: BTreeMap::new(),
+ named_parameters: vec![],
+ }
+ }
+}
+
+impl<'tcx> TypeVisitor<'tcx> for BoundVarsCollector<'tcx> {
+ fn visit_binder<T: TypeVisitable<'tcx>>(
+ &mut self,
+ t: &Binder<'tcx, T>,
+ ) -> ControlFlow<Self::BreakTy> {
+ self.binder_index.shift_in(1);
+ let result = t.super_visit_with(self);
+ self.binder_index.shift_out(1);
+ result
+ }
+
+ fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
+ match *t.kind() {
+ ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
+ match self.parameters.entry(bound_ty.var.as_u32()) {
+ Entry::Vacant(entry) => {
+ entry.insert(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General));
+ }
+ Entry::Occupied(entry) => match entry.get() {
+ chalk_ir::VariableKind::Ty(_) => {}
+ _ => panic!(),
+ },
+ }
+ }
+
+ _ => (),
+ };
+
+ t.super_visit_with(self)
+ }
+
+ fn visit_region(&mut self, r: Region<'tcx>) -> ControlFlow<Self::BreakTy> {
+ match *r {
+ ty::ReLateBound(index, br) if index == self.binder_index => match br.kind {
+ ty::BoundRegionKind::BrNamed(def_id, _name) => {
+ if !self.named_parameters.iter().any(|d| *d == def_id) {
+ self.named_parameters.push(def_id);
+ }
+ }
+
+ ty::BoundRegionKind::BrAnon(var) => match self.parameters.entry(var) {
+ Entry::Vacant(entry) => {
+ entry.insert(chalk_ir::VariableKind::Lifetime);
+ }
+ Entry::Occupied(entry) => match entry.get() {
+ chalk_ir::VariableKind::Lifetime => {}
+ _ => panic!(),
+ },
+ },
+
+ ty::BoundRegionKind::BrEnv => unimplemented!(),
+ },
+
+ ty::ReEarlyBound(_re) => {
+ // FIXME(chalk): jackh726 - I think we should always have already
+ // substituted away `ReEarlyBound`s for `ReLateBound`s, but need to confirm.
+ unimplemented!();
+ }
+
+ _ => (),
+ };
+
+ r.super_visit_with(self)
+ }
+}
+
+/// This is used to replace `BoundRegionKind::BrNamed` with `BoundRegionKind::BrAnon`.
+/// Note: we assume that we will always have room for more bound vars. (i.e. we
+/// won't ever hit the `u32` limit in `BrAnon`s).
+struct NamedBoundVarSubstitutor<'a, 'tcx> {
+ tcx: TyCtxt<'tcx>,
+ binder_index: ty::DebruijnIndex,
+ named_parameters: &'a BTreeMap<DefId, u32>,
+}
+
+impl<'a, 'tcx> NamedBoundVarSubstitutor<'a, 'tcx> {
+ fn new(tcx: TyCtxt<'tcx>, named_parameters: &'a BTreeMap<DefId, u32>) -> Self {
+ NamedBoundVarSubstitutor { tcx, binder_index: ty::INNERMOST, named_parameters }
+ }
+}
+
+impl<'a, 'tcx> TypeFolder<'tcx> for NamedBoundVarSubstitutor<'a, 'tcx> {
+ fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
+ self.tcx
+ }
+
+ fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: Binder<'tcx, T>) -> Binder<'tcx, T> {
+ self.binder_index.shift_in(1);
+ let result = t.super_fold_with(self);
+ self.binder_index.shift_out(1);
+ result
+ }
+
+ fn fold_region(&mut self, r: Region<'tcx>) -> Region<'tcx> {
+ match *r {
+ ty::ReLateBound(index, br) if index == self.binder_index => match br.kind {
+ ty::BrNamed(def_id, _name) => match self.named_parameters.get(&def_id) {
+ Some(idx) => {
+ let new_br = ty::BoundRegion { var: br.var, kind: ty::BrAnon(*idx) };
+ return self.tcx.mk_region(ty::ReLateBound(index, new_br));
+ }
+ None => panic!("Missing `BrNamed`."),
+ },
+ ty::BrEnv => unimplemented!(),
+ ty::BrAnon(_) => {}
+ },
+ _ => (),
+ };
+
+ r.super_fold_with(self)
+ }
+}
+
+/// Used to substitute `Param`s with placeholders. We do this since Chalk
+/// have a notion of `Param`s.
+pub(crate) struct ParamsSubstitutor<'tcx> {
+ tcx: TyCtxt<'tcx>,
+ binder_index: ty::DebruijnIndex,
+ list: Vec<rustc_middle::ty::ParamTy>,
+ next_ty_placeholder: usize,
+ pub(crate) params: rustc_data_structures::fx::FxHashMap<usize, rustc_middle::ty::ParamTy>,
+ pub(crate) named_regions: BTreeMap<DefId, u32>,
+}
+
+impl<'tcx> ParamsSubstitutor<'tcx> {
+ pub(crate) fn new(tcx: TyCtxt<'tcx>, next_ty_placeholder: usize) -> Self {
+ ParamsSubstitutor {
+ tcx,
+ binder_index: ty::INNERMOST,
+ list: vec![],
+ next_ty_placeholder,
+ params: rustc_data_structures::fx::FxHashMap::default(),
+ named_regions: BTreeMap::default(),
+ }
+ }
+}
+
+impl<'tcx> TypeFolder<'tcx> for ParamsSubstitutor<'tcx> {
+ fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
+ self.tcx
+ }
+
+ fn fold_binder<T: TypeFoldable<'tcx>>(&mut self, t: Binder<'tcx, T>) -> Binder<'tcx, T> {
+ self.binder_index.shift_in(1);
+ let result = t.super_fold_with(self);
+ self.binder_index.shift_out(1);
+ result
+ }
+
+ fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
+ match *t.kind() {
+ ty::Param(param) => match self.list.iter().position(|r| r == &param) {
+ Some(idx) => self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
+ universe: ty::UniverseIndex::from_usize(0),
+ name: ty::BoundVar::from_usize(idx),
+ })),
+ None => {
+ self.list.push(param);
+ let idx = self.list.len() - 1 + self.next_ty_placeholder;
+ self.params.insert(idx, param);
+ self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType {
+ universe: ty::UniverseIndex::from_usize(0),
+ name: ty::BoundVar::from_usize(idx),
+ }))
+ }
+ },
+ _ => t.super_fold_with(self),
+ }
+ }
+
+ fn fold_region(&mut self, r: Region<'tcx>) -> Region<'tcx> {
+ match *r {
+ // FIXME(chalk) - jackh726 - this currently isn't hit in any tests,
+ // since canonicalization will already change these to canonical
+ // variables (ty::ReLateBound).
+ ty::ReEarlyBound(_re) => match self.named_regions.get(&_re.def_id) {
+ Some(idx) => {
+ let br = ty::BoundRegion {
+ var: ty::BoundVar::from_u32(*idx),
+ kind: ty::BrAnon(*idx),
+ };
+ self.tcx.mk_region(ty::ReLateBound(self.binder_index, br))
+ }
+ None => {
+ let idx = self.named_regions.len() as u32;
+ let br =
+ ty::BoundRegion { var: ty::BoundVar::from_u32(idx), kind: ty::BrAnon(idx) };
+ self.named_regions.insert(_re.def_id, idx);
+ self.tcx.mk_region(ty::ReLateBound(self.binder_index, br))
+ }
+ },
+
+ _ => r.super_fold_with(self),
+ }
+ }
+}
+
+pub(crate) struct ReverseParamsSubstitutor<'tcx> {
+ tcx: TyCtxt<'tcx>,
+ params: rustc_data_structures::fx::FxHashMap<usize, rustc_middle::ty::ParamTy>,
+}
+
+impl<'tcx> ReverseParamsSubstitutor<'tcx> {
+ pub(crate) fn new(
+ tcx: TyCtxt<'tcx>,
+ params: rustc_data_structures::fx::FxHashMap<usize, rustc_middle::ty::ParamTy>,
+ ) -> Self {
+ Self { tcx, params }
+ }
+}
+
+impl<'tcx> TypeFolder<'tcx> for ReverseParamsSubstitutor<'tcx> {
+ fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
+ self.tcx
+ }
+
+ fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
+ match *t.kind() {
+ ty::Placeholder(ty::PlaceholderType { universe: ty::UniverseIndex::ROOT, name }) => {
+ match self.params.get(&name.as_usize()) {
+ Some(param) => self.tcx.mk_ty(ty::Param(*param)),
+ None => t,
+ }
+ }
+
+ _ => t.super_fold_with(self),
+ }
+ }
+}
+
+/// Used to collect `Placeholder`s.
+pub(crate) struct PlaceholdersCollector {
+ universe_index: ty::UniverseIndex,
+ pub(crate) next_ty_placeholder: usize,
+ pub(crate) next_anon_region_placeholder: u32,
+}
+
+impl PlaceholdersCollector {
+ pub(crate) fn new() -> Self {
+ PlaceholdersCollector {
+ universe_index: ty::UniverseIndex::ROOT,
+ next_ty_placeholder: 0,
+ next_anon_region_placeholder: 0,
+ }
+ }
+}
+
+impl<'tcx> TypeVisitor<'tcx> for PlaceholdersCollector {
+ fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
+ match t.kind() {
+ ty::Placeholder(p) if p.universe == self.universe_index => {
+ self.next_ty_placeholder = self.next_ty_placeholder.max(p.name.as_usize() + 1);
+ }
+
+ _ => (),
+ };
+
+ t.super_visit_with(self)
+ }
+
+ fn visit_region(&mut self, r: Region<'tcx>) -> ControlFlow<Self::BreakTy> {
+ match *r {
+ ty::RePlaceholder(p) if p.universe == self.universe_index => {
+ if let ty::BoundRegionKind::BrAnon(anon) = p.name {
+ self.next_anon_region_placeholder = self.next_anon_region_placeholder.max(anon);
+ }
+ }
+
+ _ => (),
+ };
+
+ r.super_visit_with(self)
+ }
+}
diff --git a/compiler/rustc_traits/src/chalk/mod.rs b/compiler/rustc_traits/src/chalk/mod.rs
new file mode 100644
index 000000000..f76386fa7
--- /dev/null
+++ b/compiler/rustc_traits/src/chalk/mod.rs
@@ -0,0 +1,176 @@
+//! Calls `chalk-solve` to solve a `ty::Predicate`
+//!
+//! In order to call `chalk-solve`, this file must convert a `CanonicalChalkEnvironmentAndGoal` into
+//! a Chalk uncanonical goal. It then calls Chalk, and converts the answer back into rustc solution.
+
+pub(crate) mod db;
+pub(crate) mod lowering;
+
+use rustc_data_structures::fx::FxHashMap;
+
+use rustc_index::vec::IndexVec;
+
+use rustc_middle::infer::canonical::{CanonicalTyVarKind, CanonicalVarKind};
+use rustc_middle::traits::ChalkRustInterner;
+use rustc_middle::ty::query::Providers;
+use rustc_middle::ty::subst::GenericArg;
+use rustc_middle::ty::{self, BoundVar, ParamTy, TyCtxt, TypeFoldable, TypeVisitable};
+
+use rustc_infer::infer::canonical::{
+ Canonical, CanonicalVarValues, Certainty, QueryRegionConstraints, QueryResponse,
+};
+use rustc_infer::traits::{self, CanonicalChalkEnvironmentAndGoal};
+
+use crate::chalk::db::RustIrDatabase as ChalkRustIrDatabase;
+use crate::chalk::lowering::LowerInto;
+use crate::chalk::lowering::{ParamsSubstitutor, PlaceholdersCollector, ReverseParamsSubstitutor};
+
+use chalk_solve::Solution;
+
+pub(crate) fn provide(p: &mut Providers) {
+ *p = Providers { evaluate_goal, ..*p };
+}
+
+pub(crate) fn evaluate_goal<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ obligation: CanonicalChalkEnvironmentAndGoal<'tcx>,
+) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, traits::query::NoSolution> {
+ let interner = ChalkRustInterner { tcx };
+
+ // Chalk doesn't have a notion of `Params`, so instead we use placeholders.
+ let mut placeholders_collector = PlaceholdersCollector::new();
+ obligation.visit_with(&mut placeholders_collector);
+
+ let mut params_substitutor =
+ ParamsSubstitutor::new(tcx, placeholders_collector.next_ty_placeholder);
+ let obligation = obligation.fold_with(&mut params_substitutor);
+ let params: FxHashMap<usize, ParamTy> = params_substitutor.params;
+
+ let max_universe = obligation.max_universe.index();
+
+ let lowered_goal: chalk_ir::UCanonical<
+ chalk_ir::InEnvironment<chalk_ir::Goal<ChalkRustInterner<'tcx>>>,
+ > = chalk_ir::UCanonical {
+ canonical: chalk_ir::Canonical {
+ binders: chalk_ir::CanonicalVarKinds::from_iter(
+ interner,
+ obligation.variables.iter().map(|v| match v.kind {
+ CanonicalVarKind::PlaceholderTy(_ty) => unimplemented!(),
+ CanonicalVarKind::PlaceholderRegion(_ui) => unimplemented!(),
+ CanonicalVarKind::Ty(ty) => match ty {
+ CanonicalTyVarKind::General(ui) => chalk_ir::WithKind::new(
+ chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
+ chalk_ir::UniverseIndex { counter: ui.index() },
+ ),
+ CanonicalTyVarKind::Int => chalk_ir::WithKind::new(
+ chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::Integer),
+ chalk_ir::UniverseIndex::root(),
+ ),
+ CanonicalTyVarKind::Float => chalk_ir::WithKind::new(
+ chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::Float),
+ chalk_ir::UniverseIndex::root(),
+ ),
+ },
+ CanonicalVarKind::Region(ui) => chalk_ir::WithKind::new(
+ chalk_ir::VariableKind::Lifetime,
+ chalk_ir::UniverseIndex { counter: ui.index() },
+ ),
+ CanonicalVarKind::Const(_ui, _ty) => unimplemented!(),
+ CanonicalVarKind::PlaceholderConst(_pc, _ty) => unimplemented!(),
+ }),
+ ),
+ value: obligation.value.lower_into(interner),
+ },
+ universes: max_universe + 1,
+ };
+
+ use chalk_solve::Solver;
+ let mut solver = chalk_engine::solve::SLGSolver::new(32, None);
+ let db = ChalkRustIrDatabase { interner };
+ debug!(?lowered_goal);
+ let solution = solver.solve(&db, &lowered_goal);
+ debug!(?obligation, ?solution, "evaluate goal");
+
+ // Ideally, the code to convert *back* to rustc types would live close to
+ // the code to convert *from* rustc types. Right now though, we don't
+ // really need this and so it's really minimal.
+ // Right now, we also treat a `Unique` solution the same as
+ // `Ambig(Definite)`. This really isn't right.
+ let make_solution = |subst: chalk_ir::Substitution<_>,
+ binders: chalk_ir::CanonicalVarKinds<_>| {
+ use rustc_middle::infer::canonical::CanonicalVarInfo;
+
+ let mut var_values: IndexVec<BoundVar, GenericArg<'tcx>> = IndexVec::new();
+ let mut reverse_param_substitutor = ReverseParamsSubstitutor::new(tcx, params);
+ subst.as_slice(interner).iter().for_each(|p| {
+ var_values.push(p.lower_into(interner).fold_with(&mut reverse_param_substitutor));
+ });
+ let variables: Vec<_> = binders
+ .iter(interner)
+ .map(|var| {
+ let kind = match var.kind {
+ chalk_ir::VariableKind::Ty(ty_kind) => CanonicalVarKind::Ty(match ty_kind {
+ chalk_ir::TyVariableKind::General => CanonicalTyVarKind::General(
+ ty::UniverseIndex::from_usize(var.skip_kind().counter),
+ ),
+ chalk_ir::TyVariableKind::Integer => CanonicalTyVarKind::Int,
+ chalk_ir::TyVariableKind::Float => CanonicalTyVarKind::Float,
+ }),
+ chalk_ir::VariableKind::Lifetime => CanonicalVarKind::Region(
+ ty::UniverseIndex::from_usize(var.skip_kind().counter),
+ ),
+ // FIXME(compiler-errors): We don't currently have a way of turning
+ // a Chalk ty back into a rustc ty, right?
+ chalk_ir::VariableKind::Const(_) => todo!(),
+ };
+ CanonicalVarInfo { kind }
+ })
+ .collect();
+ let max_universe = binders.iter(interner).map(|v| v.skip_kind().counter).max().unwrap_or(0);
+ let sol = Canonical {
+ max_universe: ty::UniverseIndex::from_usize(max_universe),
+ variables: tcx.intern_canonical_var_infos(&variables),
+ value: QueryResponse {
+ var_values: CanonicalVarValues { var_values },
+ region_constraints: QueryRegionConstraints::default(),
+ certainty: Certainty::Proven,
+ opaque_types: vec![],
+ value: (),
+ },
+ };
+ tcx.arena.alloc(sol)
+ };
+ solution
+ .map(|s| match s {
+ Solution::Unique(subst) => {
+ // FIXME(chalk): handle constraints
+ make_solution(subst.value.subst, subst.binders)
+ }
+ Solution::Ambig(guidance) => {
+ match guidance {
+ chalk_solve::Guidance::Definite(subst) => {
+ make_solution(subst.value, subst.binders)
+ }
+ chalk_solve::Guidance::Suggested(_) => unimplemented!(),
+ chalk_solve::Guidance::Unknown => {
+ // chalk_fulfill doesn't use the var_values here, so
+ // let's just ignore that
+ let sol = Canonical {
+ max_universe: ty::UniverseIndex::from_usize(0),
+ variables: obligation.variables,
+ value: QueryResponse {
+ var_values: CanonicalVarValues { var_values: IndexVec::new() }
+ .make_identity(tcx),
+ region_constraints: QueryRegionConstraints::default(),
+ certainty: Certainty::Ambiguous,
+ opaque_types: vec![],
+ value: (),
+ },
+ };
+ &*tcx.arena.alloc(sol)
+ }
+ }
+ }
+ })
+ .ok_or(traits::query::NoSolution)
+}
diff --git a/compiler/rustc_traits/src/dropck_outlives.rs b/compiler/rustc_traits/src/dropck_outlives.rs
new file mode 100644
index 000000000..a20de08b4
--- /dev/null
+++ b/compiler/rustc_traits/src/dropck_outlives.rs
@@ -0,0 +1,348 @@
+use rustc_data_structures::fx::FxHashSet;
+use rustc_hir::def_id::DefId;
+use rustc_infer::infer::canonical::{Canonical, QueryResponse};
+use rustc_infer::infer::TyCtxtInferExt;
+use rustc_infer::traits::TraitEngineExt as _;
+use rustc_middle::ty::query::Providers;
+use rustc_middle::ty::subst::{InternalSubsts, Subst};
+use rustc_middle::ty::{self, EarlyBinder, ParamEnvAnd, Ty, TyCtxt};
+use rustc_span::source_map::{Span, DUMMY_SP};
+use rustc_trait_selection::traits::query::dropck_outlives::trivial_dropck_outlives;
+use rustc_trait_selection::traits::query::dropck_outlives::{
+ DropckConstraint, DropckOutlivesResult,
+};
+use rustc_trait_selection::traits::query::normalize::AtExt;
+use rustc_trait_selection::traits::query::{CanonicalTyGoal, NoSolution};
+use rustc_trait_selection::traits::{
+ Normalized, ObligationCause, TraitEngine, TraitEngineExt as _,
+};
+
+pub(crate) fn provide(p: &mut Providers) {
+ *p = Providers { dropck_outlives, adt_dtorck_constraint, ..*p };
+}
+
+fn dropck_outlives<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ canonical_goal: CanonicalTyGoal<'tcx>,
+) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, DropckOutlivesResult<'tcx>>>, NoSolution> {
+ debug!("dropck_outlives(goal={:#?})", canonical_goal);
+
+ tcx.infer_ctxt().enter_with_canonical(
+ DUMMY_SP,
+ &canonical_goal,
+ |ref infcx, goal, canonical_inference_vars| {
+ let tcx = infcx.tcx;
+ let ParamEnvAnd { param_env, value: for_ty } = goal;
+
+ let mut result = DropckOutlivesResult { kinds: vec![], overflows: vec![] };
+
+ // A stack of types left to process. Each round, we pop
+ // something from the stack and invoke
+ // `dtorck_constraint_for_ty`. This may produce new types that
+ // have to be pushed on the stack. This continues until we have explored
+ // all the reachable types from the type `for_ty`.
+ //
+ // Example: Imagine that we have the following code:
+ //
+ // ```rust
+ // struct A {
+ // value: B,
+ // children: Vec<A>,
+ // }
+ //
+ // struct B {
+ // value: u32
+ // }
+ //
+ // fn f() {
+ // let a: A = ...;
+ // ..
+ // } // here, `a` is dropped
+ // ```
+ //
+ // at the point where `a` is dropped, we need to figure out
+ // which types inside of `a` contain region data that may be
+ // accessed by any destructors in `a`. We begin by pushing `A`
+ // onto the stack, as that is the type of `a`. We will then
+ // invoke `dtorck_constraint_for_ty` which will expand `A`
+ // into the types of its fields `(B, Vec<A>)`. These will get
+ // pushed onto the stack. Eventually, expanding `Vec<A>` will
+ // lead to us trying to push `A` a second time -- to prevent
+ // infinite recursion, we notice that `A` was already pushed
+ // once and stop.
+ let mut ty_stack = vec![(for_ty, 0)];
+
+ // Set used to detect infinite recursion.
+ let mut ty_set = FxHashSet::default();
+
+ let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
+
+ let cause = ObligationCause::dummy();
+ let mut constraints = DropckConstraint::empty();
+ while let Some((ty, depth)) = ty_stack.pop() {
+ debug!(
+ "{} kinds, {} overflows, {} ty_stack",
+ result.kinds.len(),
+ result.overflows.len(),
+ ty_stack.len()
+ );
+ dtorck_constraint_for_ty(tcx, DUMMY_SP, for_ty, depth, ty, &mut constraints)?;
+
+ // "outlives" represent types/regions that may be touched
+ // by a destructor.
+ result.kinds.append(&mut constraints.outlives);
+ result.overflows.append(&mut constraints.overflows);
+
+ // If we have even one overflow, we should stop trying to evaluate further --
+ // chances are, the subsequent overflows for this evaluation won't provide useful
+ // information and will just decrease the speed at which we can emit these errors
+ // (since we'll be printing for just that much longer for the often enormous types
+ // that result here).
+ if !result.overflows.is_empty() {
+ break;
+ }
+
+ // dtorck types are "types that will get dropped but which
+ // do not themselves define a destructor", more or less. We have
+ // to push them onto the stack to be expanded.
+ for ty in constraints.dtorck_types.drain(..) {
+ match infcx.at(&cause, param_env).normalize(ty) {
+ Ok(Normalized { value: ty, obligations }) => {
+ fulfill_cx.register_predicate_obligations(infcx, obligations);
+
+ debug!("dropck_outlives: ty from dtorck_types = {:?}", ty);
+
+ match ty.kind() {
+ // All parameters live for the duration of the
+ // function.
+ ty::Param(..) => {}
+
+ // A projection that we couldn't resolve - it
+ // might have a destructor.
+ ty::Projection(..) | ty::Opaque(..) => {
+ result.kinds.push(ty.into());
+ }
+
+ _ => {
+ if ty_set.insert(ty) {
+ ty_stack.push((ty, depth + 1));
+ }
+ }
+ }
+ }
+
+ // We don't actually expect to fail to normalize.
+ // That implies a WF error somewhere else.
+ Err(NoSolution) => {
+ return Err(NoSolution);
+ }
+ }
+ }
+ }
+
+ debug!("dropck_outlives: result = {:#?}", result);
+
+ infcx.make_canonicalized_query_response(
+ canonical_inference_vars,
+ result,
+ &mut *fulfill_cx,
+ )
+ },
+ )
+}
+
+/// Returns a set of constraints that needs to be satisfied in
+/// order for `ty` to be valid for destruction.
+fn dtorck_constraint_for_ty<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ span: Span,
+ for_ty: Ty<'tcx>,
+ depth: usize,
+ ty: Ty<'tcx>,
+ constraints: &mut DropckConstraint<'tcx>,
+) -> Result<(), NoSolution> {
+ debug!("dtorck_constraint_for_ty({:?}, {:?}, {:?}, {:?})", span, for_ty, depth, ty);
+
+ if !tcx.recursion_limit().value_within_limit(depth) {
+ constraints.overflows.push(ty);
+ return Ok(());
+ }
+
+ if trivial_dropck_outlives(tcx, ty) {
+ return Ok(());
+ }
+
+ match ty.kind() {
+ ty::Bool
+ | ty::Char
+ | ty::Int(_)
+ | ty::Uint(_)
+ | ty::Float(_)
+ | ty::Str
+ | ty::Never
+ | ty::Foreign(..)
+ | ty::RawPtr(..)
+ | ty::Ref(..)
+ | ty::FnDef(..)
+ | ty::FnPtr(_)
+ | ty::GeneratorWitness(..) => {
+ // these types never have a destructor
+ }
+
+ ty::Array(ety, _) | ty::Slice(ety) => {
+ // single-element containers, behave like their element
+ rustc_data_structures::stack::ensure_sufficient_stack(|| {
+ dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, *ety, constraints)
+ })?;
+ }
+
+ ty::Tuple(tys) => rustc_data_structures::stack::ensure_sufficient_stack(|| {
+ for ty in tys.iter() {
+ dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ty, constraints)?;
+ }
+ Ok::<_, NoSolution>(())
+ })?,
+
+ ty::Closure(_, substs) => {
+ if !substs.as_closure().is_valid() {
+ // By the time this code runs, all type variables ought to
+ // be fully resolved.
+
+ tcx.sess.delay_span_bug(
+ span,
+ &format!("upvar_tys for closure not found. Expected capture information for closure {}", ty,),
+ );
+ return Err(NoSolution);
+ }
+
+ rustc_data_structures::stack::ensure_sufficient_stack(|| {
+ for ty in substs.as_closure().upvar_tys() {
+ dtorck_constraint_for_ty(tcx, span, for_ty, depth + 1, ty, constraints)?;
+ }
+ Ok::<_, NoSolution>(())
+ })?
+ }
+
+ ty::Generator(_, substs, _movability) => {
+ // rust-lang/rust#49918: types can be constructed, stored
+ // in the interior, and sit idle when generator yields
+ // (and is subsequently dropped).
+ //
+ // It would be nice to descend into interior of a
+ // generator to determine what effects dropping it might
+ // have (by looking at any drop effects associated with
+ // its interior).
+ //
+ // However, the interior's representation uses things like
+ // GeneratorWitness that explicitly assume they are not
+ // traversed in such a manner. So instead, we will
+ // simplify things for now by treating all generators as
+ // if they were like trait objects, where its upvars must
+ // all be alive for the generator's (potential)
+ // destructor.
+ //
+ // In particular, skipping over `_interior` is safe
+ // because any side-effects from dropping `_interior` can
+ // only take place through references with lifetimes
+ // derived from lifetimes attached to the upvars and resume
+ // argument, and we *do* incorporate those here.
+
+ if !substs.as_generator().is_valid() {
+ // By the time this code runs, all type variables ought to
+ // be fully resolved.
+ tcx.sess.delay_span_bug(
+ span,
+ &format!("upvar_tys for generator not found. Expected capture information for generator {}", ty,),
+ );
+ return Err(NoSolution);
+ }
+
+ constraints.outlives.extend(
+ substs
+ .as_generator()
+ .upvar_tys()
+ .map(|t| -> ty::subst::GenericArg<'tcx> { t.into() }),
+ );
+ constraints.outlives.push(substs.as_generator().resume_ty().into());
+ }
+
+ ty::Adt(def, substs) => {
+ let DropckConstraint { dtorck_types, outlives, overflows } =
+ tcx.at(span).adt_dtorck_constraint(def.did())?;
+ // FIXME: we can try to recursively `dtorck_constraint_on_ty`
+ // there, but that needs some way to handle cycles.
+ constraints
+ .dtorck_types
+ .extend(dtorck_types.iter().map(|t| EarlyBinder(*t).subst(tcx, substs)));
+ constraints
+ .outlives
+ .extend(outlives.iter().map(|t| EarlyBinder(*t).subst(tcx, substs)));
+ constraints
+ .overflows
+ .extend(overflows.iter().map(|t| EarlyBinder(*t).subst(tcx, substs)));
+ }
+
+ // Objects must be alive in order for their destructor
+ // to be called.
+ ty::Dynamic(..) => {
+ constraints.outlives.push(ty.into());
+ }
+
+ // Types that can't be resolved. Pass them forward.
+ ty::Projection(..) | ty::Opaque(..) | ty::Param(..) => {
+ constraints.dtorck_types.push(ty);
+ }
+
+ ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => {
+ // By the time this code runs, all type variables ought to
+ // be fully resolved.
+ return Err(NoSolution);
+ }
+ }
+
+ Ok(())
+}
+
+/// Calculates the dtorck constraint for a type.
+pub(crate) fn adt_dtorck_constraint(
+ tcx: TyCtxt<'_>,
+ def_id: DefId,
+) -> Result<&DropckConstraint<'_>, NoSolution> {
+ let def = tcx.adt_def(def_id);
+ let span = tcx.def_span(def_id);
+ debug!("dtorck_constraint: {:?}", def);
+
+ if def.is_phantom_data() {
+ // The first generic parameter here is guaranteed to be a type because it's
+ // `PhantomData`.
+ let substs = InternalSubsts::identity_for_item(tcx, def_id);
+ assert_eq!(substs.len(), 1);
+ let result = DropckConstraint {
+ outlives: vec![],
+ dtorck_types: vec![substs.type_at(0)],
+ overflows: vec![],
+ };
+ debug!("dtorck_constraint: {:?} => {:?}", def, result);
+ return Ok(tcx.arena.alloc(result));
+ }
+
+ let mut result = DropckConstraint::empty();
+ for field in def.all_fields() {
+ let fty = tcx.type_of(field.did);
+ dtorck_constraint_for_ty(tcx, span, fty, 0, fty, &mut result)?;
+ }
+ result.outlives.extend(tcx.destructor_constraints(def));
+ dedup_dtorck_constraint(&mut result);
+
+ debug!("dtorck_constraint: {:?} => {:?}", def, result);
+
+ Ok(tcx.arena.alloc(result))
+}
+
+fn dedup_dtorck_constraint(c: &mut DropckConstraint<'_>) {
+ let mut outlives = FxHashSet::default();
+ let mut dtorck_types = FxHashSet::default();
+
+ c.outlives.retain(|&val| outlives.replace(val).is_none());
+ c.dtorck_types.retain(|&val| dtorck_types.replace(val).is_none());
+}
diff --git a/compiler/rustc_traits/src/evaluate_obligation.rs b/compiler/rustc_traits/src/evaluate_obligation.rs
new file mode 100644
index 000000000..49c9ba459
--- /dev/null
+++ b/compiler/rustc_traits/src/evaluate_obligation.rs
@@ -0,0 +1,34 @@
+use rustc_infer::infer::{DefiningAnchor, TyCtxtInferExt};
+use rustc_middle::ty::query::Providers;
+use rustc_middle::ty::{ParamEnvAnd, TyCtxt};
+use rustc_span::source_map::DUMMY_SP;
+use rustc_trait_selection::traits::query::CanonicalPredicateGoal;
+use rustc_trait_selection::traits::{
+ EvaluationResult, Obligation, ObligationCause, OverflowError, SelectionContext, TraitQueryMode,
+};
+
+pub(crate) fn provide(p: &mut Providers) {
+ *p = Providers { evaluate_obligation, ..*p };
+}
+
+fn evaluate_obligation<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ canonical_goal: CanonicalPredicateGoal<'tcx>,
+) -> Result<EvaluationResult, OverflowError> {
+ debug!("evaluate_obligation(canonical_goal={:#?})", canonical_goal);
+ // HACK This bubble is required for this tests to pass:
+ // impl-trait/issue99642.rs
+ tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bubble).enter_with_canonical(
+ DUMMY_SP,
+ &canonical_goal,
+ |ref infcx, goal, _canonical_inference_vars| {
+ debug!("evaluate_obligation: goal={:#?}", goal);
+ let ParamEnvAnd { param_env, value: predicate } = goal;
+
+ let mut selcx = SelectionContext::with_query_mode(&infcx, TraitQueryMode::Canonical);
+ let obligation = Obligation::new(ObligationCause::dummy(), param_env, predicate);
+
+ selcx.evaluate_root_obligation(&obligation)
+ },
+ )
+}
diff --git a/compiler/rustc_traits/src/implied_outlives_bounds.rs b/compiler/rustc_traits/src/implied_outlives_bounds.rs
new file mode 100644
index 000000000..e3e78f70b
--- /dev/null
+++ b/compiler/rustc_traits/src/implied_outlives_bounds.rs
@@ -0,0 +1,172 @@
+//! Provider for the `implied_outlives_bounds` query.
+//! Do not call this query directory. See
+//! [`rustc_trait_selection::traits::query::type_op::implied_outlives_bounds`].
+
+use rustc_hir as hir;
+use rustc_infer::infer::canonical::{self, Canonical};
+use rustc_infer::infer::outlives::components::{push_outlives_components, Component};
+use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
+use rustc_infer::traits::query::OutlivesBound;
+use rustc_infer::traits::TraitEngineExt as _;
+use rustc_middle::ty::query::Providers;
+use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable};
+use rustc_span::source_map::DUMMY_SP;
+use rustc_trait_selection::infer::InferCtxtBuilderExt;
+use rustc_trait_selection::traits::query::{CanonicalTyGoal, Fallible, NoSolution};
+use rustc_trait_selection::traits::wf;
+use rustc_trait_selection::traits::{TraitEngine, TraitEngineExt};
+use smallvec::{smallvec, SmallVec};
+
+pub(crate) fn provide(p: &mut Providers) {
+ *p = Providers { implied_outlives_bounds, ..*p };
+}
+
+fn implied_outlives_bounds<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ goal: CanonicalTyGoal<'tcx>,
+) -> Result<
+ &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, Vec<OutlivesBound<'tcx>>>>,
+ NoSolution,
+> {
+ tcx.infer_ctxt().enter_canonical_trait_query(&goal, |infcx, _fulfill_cx, key| {
+ let (param_env, ty) = key.into_parts();
+ compute_implied_outlives_bounds(&infcx, param_env, ty)
+ })
+}
+
+fn compute_implied_outlives_bounds<'tcx>(
+ infcx: &InferCtxt<'_, 'tcx>,
+ param_env: ty::ParamEnv<'tcx>,
+ ty: Ty<'tcx>,
+) -> Fallible<Vec<OutlivesBound<'tcx>>> {
+ let tcx = infcx.tcx;
+
+ // Sometimes when we ask what it takes for T: WF, we get back that
+ // U: WF is required; in that case, we push U onto this stack and
+ // process it next. Because the resulting predicates aren't always
+ // guaranteed to be a subset of the original type, so we need to store the
+ // WF args we've computed in a set.
+ let mut checked_wf_args = rustc_data_structures::fx::FxHashSet::default();
+ let mut wf_args = vec![ty.into()];
+
+ let mut implied_bounds = vec![];
+
+ let mut fulfill_cx = <dyn TraitEngine<'tcx>>::new(tcx);
+
+ while let Some(arg) = wf_args.pop() {
+ if !checked_wf_args.insert(arg) {
+ continue;
+ }
+
+ // Compute the obligations for `arg` to be well-formed. If `arg` is
+ // an unresolved inference variable, just substituted an empty set
+ // -- because the return type here is going to be things we *add*
+ // to the environment, it's always ok for this set to be smaller
+ // than the ultimate set. (Note: normally there won't be
+ // unresolved inference variables here anyway, but there might be
+ // during typeck under some circumstances.)
+ let obligations = wf::obligations(infcx, param_env, hir::CRATE_HIR_ID, 0, arg, DUMMY_SP)
+ .unwrap_or_default();
+
+ // N.B., all of these predicates *ought* to be easily proven
+ // true. In fact, their correctness is (mostly) implied by
+ // other parts of the program. However, in #42552, we had
+ // an annoying scenario where:
+ //
+ // - Some `T::Foo` gets normalized, resulting in a
+ // variable `_1` and a `T: Trait<Foo=_1>` constraint
+ // (not sure why it couldn't immediately get
+ // solved). This result of `_1` got cached.
+ // - These obligations were dropped on the floor here,
+ // rather than being registered.
+ // - Then later we would get a request to normalize
+ // `T::Foo` which would result in `_1` being used from
+ // the cache, but hence without the `T: Trait<Foo=_1>`
+ // constraint. As a result, `_1` never gets resolved,
+ // and we get an ICE (in dropck).
+ //
+ // Therefore, we register any predicates involving
+ // inference variables. We restrict ourselves to those
+ // involving inference variables both for efficiency and
+ // to avoids duplicate errors that otherwise show up.
+ fulfill_cx.register_predicate_obligations(
+ infcx,
+ obligations.iter().filter(|o| o.predicate.has_infer_types_or_consts()).cloned(),
+ );
+
+ // From the full set of obligations, just filter down to the
+ // region relationships.
+ implied_bounds.extend(obligations.into_iter().flat_map(|obligation| {
+ assert!(!obligation.has_escaping_bound_vars());
+ match obligation.predicate.kind().no_bound_vars() {
+ None => vec![],
+ Some(pred) => match pred {
+ ty::PredicateKind::Trait(..)
+ | ty::PredicateKind::Subtype(..)
+ | ty::PredicateKind::Coerce(..)
+ | ty::PredicateKind::Projection(..)
+ | ty::PredicateKind::ClosureKind(..)
+ | ty::PredicateKind::ObjectSafe(..)
+ | ty::PredicateKind::ConstEvaluatable(..)
+ | ty::PredicateKind::ConstEquate(..)
+ | ty::PredicateKind::TypeWellFormedFromEnv(..) => vec![],
+ ty::PredicateKind::WellFormed(arg) => {
+ wf_args.push(arg);
+ vec![]
+ }
+
+ ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(r_a, r_b)) => {
+ vec![OutlivesBound::RegionSubRegion(r_b, r_a)]
+ }
+
+ ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_a, r_b)) => {
+ let ty_a = infcx.resolve_vars_if_possible(ty_a);
+ let mut components = smallvec![];
+ push_outlives_components(tcx, ty_a, &mut components);
+ implied_bounds_from_components(r_b, components)
+ }
+ },
+ }
+ }));
+ }
+
+ // Ensure that those obligations that we had to solve
+ // get solved *here*.
+ match fulfill_cx.select_all_or_error(infcx).as_slice() {
+ [] => Ok(implied_bounds),
+ _ => Err(NoSolution),
+ }
+}
+
+/// When we have an implied bound that `T: 'a`, we can further break
+/// this down to determine what relationships would have to hold for
+/// `T: 'a` to hold. We get to assume that the caller has validated
+/// those relationships.
+fn implied_bounds_from_components<'tcx>(
+ sub_region: ty::Region<'tcx>,
+ sup_components: SmallVec<[Component<'tcx>; 4]>,
+) -> Vec<OutlivesBound<'tcx>> {
+ sup_components
+ .into_iter()
+ .filter_map(|component| {
+ match component {
+ Component::Region(r) => Some(OutlivesBound::RegionSubRegion(sub_region, r)),
+ Component::Param(p) => Some(OutlivesBound::RegionSubParam(sub_region, p)),
+ Component::Projection(p) => Some(OutlivesBound::RegionSubProjection(sub_region, p)),
+ Component::EscapingProjection(_) =>
+ // If the projection has escaping regions, don't
+ // try to infer any implied bounds even for its
+ // free components. This is conservative, because
+ // the caller will still have to prove that those
+ // free components outlive `sub_region`. But the
+ // idea is that the WAY that the caller proves
+ // that may change in the future and we want to
+ // give ourselves room to get smarter here.
+ {
+ None
+ }
+ Component::UnresolvedInferenceVariable(..) => None,
+ }
+ })
+ .collect()
+}
diff --git a/compiler/rustc_traits/src/lib.rs b/compiler/rustc_traits/src/lib.rs
new file mode 100644
index 000000000..2bea164c0
--- /dev/null
+++ b/compiler/rustc_traits/src/lib.rs
@@ -0,0 +1,32 @@
+//! New recursive solver modeled on Chalk's recursive solver. Most of
+//! the guts are broken up into modules; see the comments in those modules.
+
+#![feature(let_else)]
+#![recursion_limit = "256"]
+
+#[macro_use]
+extern crate tracing;
+#[macro_use]
+extern crate rustc_middle;
+
+mod chalk;
+mod dropck_outlives;
+mod evaluate_obligation;
+mod implied_outlives_bounds;
+mod normalize_erasing_regions;
+mod normalize_projection_ty;
+mod type_op;
+
+pub use type_op::{type_op_ascribe_user_type_with_span, type_op_prove_predicate_with_cause};
+
+use rustc_middle::ty::query::Providers;
+
+pub fn provide(p: &mut Providers) {
+ dropck_outlives::provide(p);
+ evaluate_obligation::provide(p);
+ implied_outlives_bounds::provide(p);
+ chalk::provide(p);
+ normalize_projection_ty::provide(p);
+ normalize_erasing_regions::provide(p);
+ type_op::provide(p);
+}
diff --git a/compiler/rustc_traits/src/normalize_erasing_regions.rs b/compiler/rustc_traits/src/normalize_erasing_regions.rs
new file mode 100644
index 000000000..5d394ed22
--- /dev/null
+++ b/compiler/rustc_traits/src/normalize_erasing_regions.rs
@@ -0,0 +1,73 @@
+use rustc_infer::infer::TyCtxtInferExt;
+use rustc_middle::traits::query::NoSolution;
+use rustc_middle::ty::query::Providers;
+use rustc_middle::ty::{self, ParamEnvAnd, TyCtxt, TypeFoldable};
+use rustc_trait_selection::traits::query::normalize::AtExt;
+use rustc_trait_selection::traits::{Normalized, ObligationCause};
+use std::sync::atomic::Ordering;
+
+pub(crate) fn provide(p: &mut Providers) {
+ *p = Providers {
+ try_normalize_generic_arg_after_erasing_regions: |tcx, goal| {
+ debug!("try_normalize_generic_arg_after_erasing_regions(goal={:#?}", goal);
+
+ tcx.sess
+ .perf_stats
+ .normalize_generic_arg_after_erasing_regions
+ .fetch_add(1, Ordering::Relaxed);
+
+ try_normalize_after_erasing_regions(tcx, goal)
+ },
+ try_normalize_mir_const_after_erasing_regions: |tcx, goal| {
+ try_normalize_after_erasing_regions(tcx, goal)
+ },
+ ..*p
+ };
+}
+
+fn try_normalize_after_erasing_regions<'tcx, T: TypeFoldable<'tcx> + PartialEq + Copy>(
+ tcx: TyCtxt<'tcx>,
+ goal: ParamEnvAnd<'tcx, T>,
+) -> Result<T, NoSolution> {
+ let ParamEnvAnd { param_env, value } = goal;
+ tcx.infer_ctxt().enter(|infcx| {
+ let cause = ObligationCause::dummy();
+ match infcx.at(&cause, param_env).normalize(value) {
+ Ok(Normalized { value: normalized_value, obligations: normalized_obligations }) => {
+ // We don't care about the `obligations`; they are
+ // always only region relations, and we are about to
+ // erase those anyway:
+ debug_assert_eq!(
+ normalized_obligations.iter().find(|p| not_outlives_predicate(p.predicate)),
+ None,
+ );
+
+ let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
+ // It's unclear when `resolve_vars` would have an effect in a
+ // fresh `InferCtxt`. If this assert does trigger, it will give
+ // us a test case.
+ debug_assert_eq!(normalized_value, resolved_value);
+ let erased = infcx.tcx.erase_regions(resolved_value);
+ debug_assert!(!erased.needs_infer(), "{:?}", erased);
+ Ok(erased)
+ }
+ Err(NoSolution) => Err(NoSolution),
+ }
+ })
+}
+
+fn not_outlives_predicate<'tcx>(p: ty::Predicate<'tcx>) -> bool {
+ match p.kind().skip_binder() {
+ ty::PredicateKind::RegionOutlives(..) | ty::PredicateKind::TypeOutlives(..) => false,
+ ty::PredicateKind::Trait(..)
+ | ty::PredicateKind::Projection(..)
+ | ty::PredicateKind::WellFormed(..)
+ | ty::PredicateKind::ObjectSafe(..)
+ | ty::PredicateKind::ClosureKind(..)
+ | ty::PredicateKind::Subtype(..)
+ | ty::PredicateKind::Coerce(..)
+ | ty::PredicateKind::ConstEvaluatable(..)
+ | ty::PredicateKind::ConstEquate(..)
+ | ty::PredicateKind::TypeWellFormedFromEnv(..) => true,
+ }
+}
diff --git a/compiler/rustc_traits/src/normalize_projection_ty.rs b/compiler/rustc_traits/src/normalize_projection_ty.rs
new file mode 100644
index 000000000..98bb42c9a
--- /dev/null
+++ b/compiler/rustc_traits/src/normalize_projection_ty.rs
@@ -0,0 +1,45 @@
+use rustc_infer::infer::canonical::{Canonical, QueryResponse};
+use rustc_infer::infer::TyCtxtInferExt;
+use rustc_infer::traits::TraitEngineExt as _;
+use rustc_middle::ty::query::Providers;
+use rustc_middle::ty::{ParamEnvAnd, TyCtxt};
+use rustc_trait_selection::infer::InferCtxtBuilderExt;
+use rustc_trait_selection::traits::query::{
+ normalize::NormalizationResult, CanonicalProjectionGoal, NoSolution,
+};
+use rustc_trait_selection::traits::{self, ObligationCause, SelectionContext};
+use std::sync::atomic::Ordering;
+
+pub(crate) fn provide(p: &mut Providers) {
+ *p = Providers { normalize_projection_ty, ..*p };
+}
+
+fn normalize_projection_ty<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ goal: CanonicalProjectionGoal<'tcx>,
+) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, NormalizationResult<'tcx>>>, NoSolution> {
+ debug!("normalize_provider(goal={:#?})", goal);
+
+ tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering::Relaxed);
+ tcx.infer_ctxt().enter_canonical_trait_query(
+ &goal,
+ |infcx, fulfill_cx, ParamEnvAnd { param_env, value: goal }| {
+ let selcx = &mut SelectionContext::new(infcx);
+ let cause = ObligationCause::dummy();
+ let mut obligations = vec![];
+ let answer = traits::normalize_projection_type(
+ selcx,
+ param_env,
+ goal,
+ cause,
+ 0,
+ &mut obligations,
+ );
+ fulfill_cx.register_predicate_obligations(infcx, obligations);
+ // FIXME(associated_const_equality): All users of normalize_projection_ty expected
+ // a type, but there is the possibility it could've been a const now. Maybe change
+ // it to a Term later?
+ Ok(NormalizationResult { normalized_ty: answer.ty().unwrap() })
+ },
+ )
+}
diff --git a/compiler/rustc_traits/src/type_op.rs b/compiler/rustc_traits/src/type_op.rs
new file mode 100644
index 000000000..d895b647d
--- /dev/null
+++ b/compiler/rustc_traits/src/type_op.rs
@@ -0,0 +1,283 @@
+use rustc_hir as hir;
+use rustc_hir::def_id::DefId;
+use rustc_infer::infer::at::ToTrace;
+use rustc_infer::infer::canonical::{Canonical, QueryResponse};
+use rustc_infer::infer::{DefiningAnchor, InferCtxt, TyCtxtInferExt};
+use rustc_infer::traits::TraitEngineExt as _;
+use rustc_middle::ty::query::Providers;
+use rustc_middle::ty::subst::{GenericArg, Subst, UserSelfTy, UserSubsts};
+use rustc_middle::ty::{
+ self, EarlyBinder, FnSig, Lift, PolyFnSig, Ty, TyCtxt, TypeFoldable, Variance,
+};
+use rustc_middle::ty::{ParamEnv, ParamEnvAnd, Predicate, ToPredicate};
+use rustc_span::{Span, DUMMY_SP};
+use rustc_trait_selection::infer::InferCtxtBuilderExt;
+use rustc_trait_selection::infer::InferCtxtExt;
+use rustc_trait_selection::traits::query::normalize::AtExt;
+use rustc_trait_selection::traits::query::type_op::ascribe_user_type::AscribeUserType;
+use rustc_trait_selection::traits::query::type_op::eq::Eq;
+use rustc_trait_selection::traits::query::type_op::normalize::Normalize;
+use rustc_trait_selection::traits::query::type_op::prove_predicate::ProvePredicate;
+use rustc_trait_selection::traits::query::type_op::subtype::Subtype;
+use rustc_trait_selection::traits::query::{Fallible, NoSolution};
+use rustc_trait_selection::traits::{Normalized, Obligation, ObligationCause, TraitEngine};
+use std::fmt;
+
+pub(crate) fn provide(p: &mut Providers) {
+ *p = Providers {
+ type_op_ascribe_user_type,
+ type_op_eq,
+ type_op_prove_predicate,
+ type_op_subtype,
+ type_op_normalize_ty,
+ type_op_normalize_predicate,
+ type_op_normalize_fn_sig,
+ type_op_normalize_poly_fn_sig,
+ ..*p
+ };
+}
+
+fn type_op_ascribe_user_type<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, AscribeUserType<'tcx>>>,
+) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
+ tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| {
+ type_op_ascribe_user_type_with_span(infcx, fulfill_cx, key, None)
+ })
+}
+
+/// The core of the `type_op_ascribe_user_type` query: for diagnostics purposes in NLL HRTB errors,
+/// this query can be re-run to better track the span of the obligation cause, and improve the error
+/// message. Do not call directly unless you're in that very specific context.
+pub fn type_op_ascribe_user_type_with_span<'a, 'tcx: 'a>(
+ infcx: &'a InferCtxt<'a, 'tcx>,
+ fulfill_cx: &'a mut dyn TraitEngine<'tcx>,
+ key: ParamEnvAnd<'tcx, AscribeUserType<'tcx>>,
+ span: Option<Span>,
+) -> Result<(), NoSolution> {
+ let (param_env, AscribeUserType { mir_ty, def_id, user_substs }) = key.into_parts();
+ debug!(
+ "type_op_ascribe_user_type: mir_ty={:?} def_id={:?} user_substs={:?}",
+ mir_ty, def_id, user_substs
+ );
+
+ let mut cx = AscribeUserTypeCx { infcx, param_env, fulfill_cx };
+ cx.relate_mir_and_user_ty(mir_ty, def_id, user_substs, span)?;
+ Ok(())
+}
+
+struct AscribeUserTypeCx<'me, 'tcx> {
+ infcx: &'me InferCtxt<'me, 'tcx>,
+ param_env: ParamEnv<'tcx>,
+ fulfill_cx: &'me mut dyn TraitEngine<'tcx>,
+}
+
+impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
+ fn normalize<T>(&mut self, value: T) -> T
+ where
+ T: TypeFoldable<'tcx>,
+ {
+ self.infcx
+ .partially_normalize_associated_types_in(
+ ObligationCause::misc(DUMMY_SP, hir::CRATE_HIR_ID),
+ self.param_env,
+ value,
+ )
+ .into_value_registering_obligations(self.infcx, self.fulfill_cx)
+ }
+
+ fn relate<T>(&mut self, a: T, variance: Variance, b: T) -> Result<(), NoSolution>
+ where
+ T: ToTrace<'tcx>,
+ {
+ self.infcx
+ .at(&ObligationCause::dummy(), self.param_env)
+ .relate(a, variance, b)?
+ .into_value_registering_obligations(self.infcx, self.fulfill_cx);
+ Ok(())
+ }
+
+ fn prove_predicate(&mut self, predicate: Predicate<'tcx>, span: Option<Span>) {
+ let cause = if let Some(span) = span {
+ ObligationCause::dummy_with_span(span)
+ } else {
+ ObligationCause::dummy()
+ };
+ self.fulfill_cx.register_predicate_obligation(
+ self.infcx,
+ Obligation::new(cause, self.param_env, predicate),
+ );
+ }
+
+ fn tcx(&self) -> TyCtxt<'tcx> {
+ self.infcx.tcx
+ }
+
+ fn subst<T>(&self, value: T, substs: &[GenericArg<'tcx>]) -> T
+ where
+ T: TypeFoldable<'tcx>,
+ {
+ EarlyBinder(value).subst(self.tcx(), substs)
+ }
+
+ fn relate_mir_and_user_ty(
+ &mut self,
+ mir_ty: Ty<'tcx>,
+ def_id: DefId,
+ user_substs: UserSubsts<'tcx>,
+ span: Option<Span>,
+ ) -> Result<(), NoSolution> {
+ let UserSubsts { user_self_ty, substs } = user_substs;
+ let tcx = self.tcx();
+
+ let ty = tcx.type_of(def_id);
+ let ty = self.subst(ty, substs);
+ debug!("relate_type_and_user_type: ty of def-id is {:?}", ty);
+ let ty = self.normalize(ty);
+
+ self.relate(mir_ty, Variance::Invariant, ty)?;
+
+ // Prove the predicates coming along with `def_id`.
+ //
+ // Also, normalize the `instantiated_predicates`
+ // because otherwise we wind up with duplicate "type
+ // outlives" error messages.
+ let instantiated_predicates =
+ self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
+ debug!(?instantiated_predicates.predicates);
+ for instantiated_predicate in instantiated_predicates.predicates {
+ let instantiated_predicate = self.normalize(instantiated_predicate);
+ self.prove_predicate(instantiated_predicate, span);
+ }
+
+ if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
+ let impl_self_ty = self.tcx().type_of(impl_def_id);
+ let impl_self_ty = self.subst(impl_self_ty, &substs);
+ let impl_self_ty = self.normalize(impl_self_ty);
+
+ self.relate(self_ty, Variance::Invariant, impl_self_ty)?;
+
+ self.prove_predicate(
+ ty::Binder::dummy(ty::PredicateKind::WellFormed(impl_self_ty.into()))
+ .to_predicate(self.tcx()),
+ span,
+ );
+ }
+
+ // In addition to proving the predicates, we have to
+ // prove that `ty` is well-formed -- this is because
+ // the WF of `ty` is predicated on the substs being
+ // well-formed, and we haven't proven *that*. We don't
+ // want to prove the WF of types from `substs` directly because they
+ // haven't been normalized.
+ //
+ // FIXME(nmatsakis): Well, perhaps we should normalize
+ // them? This would only be relevant if some input
+ // type were ill-formed but did not appear in `ty`,
+ // which...could happen with normalization...
+ self.prove_predicate(
+ ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into())).to_predicate(self.tcx()),
+ span,
+ );
+ Ok(())
+ }
+}
+
+fn type_op_eq<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Eq<'tcx>>>,
+) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
+ tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| {
+ let (param_env, Eq { a, b }) = key.into_parts();
+ infcx
+ .at(&ObligationCause::dummy(), param_env)
+ .eq(a, b)?
+ .into_value_registering_obligations(infcx, fulfill_cx);
+ Ok(())
+ })
+}
+
+fn type_op_normalize<'tcx, T>(
+ infcx: &InferCtxt<'_, 'tcx>,
+ fulfill_cx: &mut dyn TraitEngine<'tcx>,
+ key: ParamEnvAnd<'tcx, Normalize<T>>,
+) -> Fallible<T>
+where
+ T: fmt::Debug + TypeFoldable<'tcx> + Lift<'tcx>,
+{
+ let (param_env, Normalize { value }) = key.into_parts();
+ let Normalized { value, obligations } =
+ infcx.at(&ObligationCause::dummy(), param_env).normalize(value)?;
+ fulfill_cx.register_predicate_obligations(infcx, obligations);
+ Ok(value)
+}
+
+fn type_op_normalize_ty<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<Ty<'tcx>>>>,
+) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>, NoSolution> {
+ tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
+}
+
+fn type_op_normalize_predicate<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<Predicate<'tcx>>>>,
+) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, Predicate<'tcx>>>, NoSolution> {
+ tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
+}
+
+fn type_op_normalize_fn_sig<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<FnSig<'tcx>>>>,
+) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, FnSig<'tcx>>>, NoSolution> {
+ tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
+}
+
+fn type_op_normalize_poly_fn_sig<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Normalize<PolyFnSig<'tcx>>>>,
+) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, PolyFnSig<'tcx>>>, NoSolution> {
+ tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, type_op_normalize)
+}
+
+fn type_op_subtype<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Subtype<'tcx>>>,
+) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
+ tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| {
+ let (param_env, Subtype { sub, sup }) = key.into_parts();
+ infcx
+ .at(&ObligationCause::dummy(), param_env)
+ .sup(sup, sub)?
+ .into_value_registering_obligations(infcx, fulfill_cx);
+ Ok(())
+ })
+}
+
+fn type_op_prove_predicate<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, ProvePredicate<'tcx>>>,
+) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
+ // HACK This bubble is required for this test to pass:
+ // impl-trait/issue-99642.rs
+ tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bubble).enter_canonical_trait_query(
+ &canonicalized,
+ |infcx, fulfill_cx, key| {
+ type_op_prove_predicate_with_cause(infcx, fulfill_cx, key, ObligationCause::dummy());
+ Ok(())
+ },
+ )
+}
+
+/// The core of the `type_op_prove_predicate` query: for diagnostics purposes in NLL HRTB errors,
+/// this query can be re-run to better track the span of the obligation cause, and improve the error
+/// message. Do not call directly unless you're in that very specific context.
+pub fn type_op_prove_predicate_with_cause<'a, 'tcx: 'a>(
+ infcx: &'a InferCtxt<'a, 'tcx>,
+ fulfill_cx: &'a mut dyn TraitEngine<'tcx>,
+ key: ParamEnvAnd<'tcx, ProvePredicate<'tcx>>,
+ cause: ObligationCause<'tcx>,
+) {
+ let (param_env, ProvePredicate { predicate }) = key.into_parts();
+ fulfill_cx.register_predicate_obligation(infcx, Obligation::new(cause, param_env, predicate));
+}