5401: Implement Chalk closure support r=matklad a=flodiebold

This makes use of Chalk's closure support, which means we can get rid of our last built-in impls and a bunch of other surrounding stuff.

Co-authored-by: Florian Diebold <flodiebold@gmail.com>
This commit is contained in:
bors[bot] 2020-07-16 08:02:39 +00:00 committed by GitHub
commit 6a74a91713
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 108 additions and 387 deletions

View File

@ -17,9 +17,9 @@
AssociatedTyDataQuery, AssociatedTyValueQuery, CallableItemSignatureQuery, FieldTypesQuery,
GenericDefaultsQuery, GenericPredicatesForParamQuery, GenericPredicatesQuery, HirDatabase,
HirDatabaseStorage, ImplDatumQuery, ImplSelfTyQuery, ImplTraitQuery, InferQueryQuery,
InherentImplsInCrateQuery, InternAssocTyValueQuery, InternChalkImplQuery, InternTypeCtorQuery,
InternTypeParamIdQuery, ReturnTypeImplTraitsQuery, StructDatumQuery, TraitDatumQuery,
TraitImplsInCrateQuery, TraitImplsInDepsQuery, TraitSolveQuery, TyQuery, ValueTyQuery,
InherentImplsInCrateQuery, InternTypeParamIdQuery, ReturnTypeImplTraitsQuery, StructDatumQuery,
TraitDatumQuery, TraitImplsInCrateQuery, TraitImplsInDepsQuery, TraitSolveQuery, TyQuery,
ValueTyQuery,
};
#[test]

View File

@ -159,17 +159,17 @@ fn lookup(&self, db: &dyn db::DefDatabase) -> $loc {
type FunctionLoc = AssocItemLoc<Function>;
impl_intern!(FunctionId, FunctionLoc, intern_function, lookup_intern_function);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct StructId(salsa::InternId);
type StructLoc = ItemLoc<Struct>;
impl_intern!(StructId, StructLoc, intern_struct, lookup_intern_struct);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct UnionId(salsa::InternId);
pub type UnionLoc = ItemLoc<Union>;
impl_intern!(UnionId, UnionLoc, intern_union, lookup_intern_union);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EnumId(salsa::InternId);
pub type EnumLoc = ItemLoc<Enum>;
impl_intern!(EnumId, EnumLoc, intern_enum, lookup_intern_enum);
@ -239,7 +239,7 @@ pub enum AssocContainerId {
impl_from!(ContainerId for AssocContainerId);
/// A Data Type
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum AdtId {
StructId(StructId),
UnionId(UnionId),

View File

@ -3,8 +3,8 @@
use std::sync::Arc;
use hir_def::{
db::DefDatabase, DefWithBodyId, FunctionId, GenericDefId, ImplId, LocalFieldId, TypeParamId,
VariantId,
db::DefDatabase, expr::ExprId, DefWithBodyId, FunctionId, GenericDefId, ImplId, LocalFieldId,
TypeParamId, VariantId,
};
use ra_arena::map::ArenaMap;
use ra_db::{impl_intern_key, salsa, CrateId, Upcast};
@ -12,9 +12,9 @@
use crate::{
method_resolution::{InherentImpls, TraitImpls},
traits::{chalk, AssocTyValue, Impl},
traits::chalk,
Binders, CallableDef, GenericPredicate, InferenceResult, OpaqueTyId, PolyFnSig,
ReturnTypeImplTraits, TraitRef, Ty, TyDefId, TypeCtor, ValueTyDefId,
ReturnTypeImplTraits, TraitRef, Ty, TyDefId, ValueTyDefId,
};
use hir_expand::name::Name;
@ -77,17 +77,13 @@ fn generic_predicates_for_param(
// Interned IDs for Chalk integration
#[salsa::interned]
fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::TypeCtorId;
#[salsa::interned]
fn intern_callable_def(&self, callable_def: CallableDef) -> crate::CallableDefId;
#[salsa::interned]
fn intern_type_param_id(&self, param_id: TypeParamId) -> GlobalTypeParamId;
#[salsa::interned]
fn intern_impl_trait_id(&self, id: OpaqueTyId) -> InternedOpaqueTyId;
#[salsa::interned]
fn intern_chalk_impl(&self, impl_: Impl) -> crate::traits::GlobalImplId;
#[salsa::interned]
fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> crate::traits::AssocTyValueId;
fn intern_closure(&self, id: (DefWithBodyId, ExprId)) -> ClosureId;
#[salsa::invoke(chalk::associated_ty_data_query)]
fn associated_ty_data(&self, id: chalk::AssocTypeId) -> Arc<chalk::AssociatedTyDatum>;
@ -151,3 +147,7 @@ fn _assert_object_safe(_: &dyn HirDatabase) {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InternedOpaqueTyId(salsa::InternId);
impl_intern_key!(InternedOpaqueTyId);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClosureId(salsa::InternId);
impl_intern_key!(ClosureId);

View File

@ -112,6 +112,7 @@ pub enum TypeCtor {
/// fn foo() -> i32 { 1 }
/// let bar: fn() -> i32 = foo;
/// ```
// FIXME make this a Ty variant like in Chalk
FnPtr { num_args: u16, is_varargs: bool },
/// The never type `!`.
@ -139,13 +140,6 @@ pub enum TypeCtor {
Closure { def: DefWithBodyId, expr: ExprId },
}
/// This exists just for Chalk, because Chalk just has a single `StructId` where
/// we have different kinds of ADTs, primitive types and special type
/// constructors like tuples and function pointers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct TypeCtorId(salsa::InternId);
impl_intern_key!(TypeCtorId);
/// This exists just for Chalk, because Chalk just has a single `FnDefId` where
/// we have different IDs for struct and enum variant constructors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]

View File

@ -40,7 +40,11 @@ fn setup_tracing() -> tracing::subscriber::DefaultGuard {
use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
use tracing_tree::HierarchicalLayer;
let filter = EnvFilter::from_env("CHALK_DEBUG");
let layer = HierarchicalLayer::default().with_indent_amount(2).with_writer(std::io::stderr);
let layer = HierarchicalLayer::default()
.with_indent_lines(true)
.with_ansi(false)
.with_indent_amount(2)
.with_writer(std::io::stderr);
let subscriber = Registry::default().with(filter).with(layer);
tracing::subscriber::set_default(subscriber)
}

View File

@ -3,10 +3,8 @@
use chalk_ir::cast::Cast;
use chalk_solve::Solver;
use hir_def::{
expr::ExprId, lang_item::LangItemTarget, DefWithBodyId, ImplId, TraitId, TypeAliasId,
};
use ra_db::{impl_intern_key, salsa, CrateId};
use hir_def::{lang_item::LangItemTarget, TraitId};
use ra_db::CrateId;
use ra_prof::profile;
use crate::{db::HirDatabase, DebruijnIndex, Substs};
@ -16,7 +14,6 @@
use self::chalk::{from_chalk, Interner, ToChalk};
pub(crate) mod chalk;
mod builtin;
// This controls the maximum size of types Chalk considers. If we set this too
// high, we can run into slow edge cases; if we set it too low, Chalk won't
@ -274,47 +271,3 @@ pub fn get_id(&self, db: &dyn HirDatabase, krate: CrateId) -> Option<TraitId> {
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClosureFnTraitImplData {
def: DefWithBodyId,
expr: ExprId,
fn_trait: FnTrait,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UnsizeToSuperTraitObjectData {
trait_: TraitId,
super_trait: TraitId,
}
/// An impl. Usually this comes from an impl block, but some built-in types get
/// synthetic impls.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Impl {
/// A normal impl from an impl block.
ImplDef(ImplId),
/// Closure types implement the Fn traits synthetically.
// FIXME: implement closure support from Chalk, remove this
ClosureFnTraitImpl(ClosureFnTraitImplData),
}
/// This exists just for Chalk, because our ImplIds are only unique per module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GlobalImplId(salsa::InternId);
impl_intern_key!(GlobalImplId);
/// An associated type value. Usually this comes from a `type` declaration
/// inside an impl block, but for built-in impls we have to synthesize it.
/// (We only need this because Chalk wants a unique ID for each of these.)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AssocTyValue {
/// A normal assoc type value from an impl block.
TypeAlias(TypeAliasId),
/// The output type of the Fn trait implementation.
ClosureFnTraitImplOutput(ClosureFnTraitImplData),
}
/// This exists just for Chalk, because it needs a unique ID for each associated
/// type value in an impl (even synthetic ones).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AssocTyValueId(salsa::InternId);
impl_intern_key!(AssocTyValueId);

View File

@ -1,178 +0,0 @@
//! This module provides the built-in trait implementations, e.g. to make
//! closures implement `Fn`.
use hir_def::{expr::Expr, TraitId, TypeAliasId};
use hir_expand::name::name;
use ra_db::CrateId;
use super::{AssocTyValue, Impl};
use crate::{
db::HirDatabase, ApplicationTy, BoundVar, DebruijnIndex, Substs, TraitRef, Ty, TypeCtor,
};
pub(super) struct BuiltinImplData {
pub num_vars: usize,
pub trait_ref: TraitRef,
pub where_clauses: Vec<super::GenericPredicate>,
pub assoc_ty_values: Vec<AssocTyValue>,
}
pub(super) struct BuiltinImplAssocTyValueData {
pub impl_: Impl,
pub assoc_ty_id: TypeAliasId,
pub num_vars: usize,
pub value: Ty,
}
pub(super) fn get_builtin_impls(
db: &dyn HirDatabase,
krate: CrateId,
ty: &Ty,
// The first argument for the trait, if present
_arg: &Option<Ty>,
trait_: TraitId,
mut callback: impl FnMut(Impl),
) {
// Note: since impl_datum needs to be infallible, we need to make sure here
// that we have all prerequisites to build the respective impls.
if let Ty::Apply(ApplicationTy { ctor: TypeCtor::Closure { def, expr }, .. }) = ty {
for &fn_trait in [super::FnTrait::FnOnce, super::FnTrait::FnMut, super::FnTrait::Fn].iter()
{
if let Some(actual_trait) = fn_trait.get_id(db, krate) {
if trait_ == actual_trait {
let impl_ = super::ClosureFnTraitImplData { def: *def, expr: *expr, fn_trait };
if check_closure_fn_trait_impl_prerequisites(db, krate, impl_) {
callback(Impl::ClosureFnTraitImpl(impl_));
}
}
}
}
}
}
pub(super) fn impl_datum(db: &dyn HirDatabase, krate: CrateId, impl_: Impl) -> BuiltinImplData {
match impl_ {
Impl::ImplDef(_) => unreachable!(),
Impl::ClosureFnTraitImpl(data) => closure_fn_trait_impl_datum(db, krate, data),
}
}
pub(super) fn associated_ty_value(
db: &dyn HirDatabase,
krate: CrateId,
data: AssocTyValue,
) -> BuiltinImplAssocTyValueData {
match data {
AssocTyValue::TypeAlias(_) => unreachable!(),
AssocTyValue::ClosureFnTraitImplOutput(data) => {
closure_fn_trait_output_assoc_ty_value(db, krate, data)
}
}
}
// Closure Fn trait impls
fn check_closure_fn_trait_impl_prerequisites(
db: &dyn HirDatabase,
krate: CrateId,
data: super::ClosureFnTraitImplData,
) -> bool {
// the respective Fn/FnOnce/FnMut trait needs to exist
if data.fn_trait.get_id(db, krate).is_none() {
return false;
}
// FIXME: there are more assumptions that we should probably check here:
// the traits having no type params, FnOnce being a supertrait
// the FnOnce trait needs to exist and have an assoc type named Output
let fn_once_trait = match (super::FnTrait::FnOnce).get_id(db, krate) {
Some(t) => t,
None => return false,
};
db.trait_data(fn_once_trait).associated_type_by_name(&name![Output]).is_some()
}
fn closure_fn_trait_impl_datum(
db: &dyn HirDatabase,
krate: CrateId,
data: super::ClosureFnTraitImplData,
) -> BuiltinImplData {
// for some closure |X, Y| -> Z:
// impl<T, U, V> Fn<(T, U)> for closure<fn(T, U) -> V> { Output = V }
let trait_ = data
.fn_trait
.get_id(db, krate) // get corresponding fn trait
// the existence of the Fn trait has been checked before
.expect("fn trait for closure impl missing");
let num_args: u16 = match &db.body(data.def)[data.expr] {
Expr::Lambda { args, .. } => args.len() as u16,
_ => {
log::warn!("closure for closure type {:?} not found", data);
0
}
};
let arg_ty = Ty::apply(
TypeCtor::Tuple { cardinality: num_args },
Substs::builder(num_args as usize)
.fill_with_bound_vars(DebruijnIndex::INNERMOST, 0)
.build(),
);
let sig_ty = Ty::apply(
TypeCtor::FnPtr { num_args, is_varargs: false },
Substs::builder(num_args as usize + 1)
.fill_with_bound_vars(DebruijnIndex::INNERMOST, 0)
.build(),
);
let self_ty = Ty::apply_one(TypeCtor::Closure { def: data.def, expr: data.expr }, sig_ty);
let trait_ref = TraitRef {
trait_,
substs: Substs::build_for_def(db, trait_).push(self_ty).push(arg_ty).build(),
};
let output_ty_id = AssocTyValue::ClosureFnTraitImplOutput(data);
BuiltinImplData {
num_vars: num_args as usize + 1,
trait_ref,
where_clauses: Vec::new(),
assoc_ty_values: vec![output_ty_id],
}
}
fn closure_fn_trait_output_assoc_ty_value(
db: &dyn HirDatabase,
krate: CrateId,
data: super::ClosureFnTraitImplData,
) -> BuiltinImplAssocTyValueData {
let impl_ = Impl::ClosureFnTraitImpl(data);
let num_args: u16 = match &db.body(data.def)[data.expr] {
Expr::Lambda { args, .. } => args.len() as u16,
_ => {
log::warn!("closure for closure type {:?} not found", data);
0
}
};
let output_ty = Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, num_args.into()));
let fn_once_trait =
(super::FnTrait::FnOnce).get_id(db, krate).expect("assoc ty value should not exist");
let output_ty_id = db
.trait_data(fn_once_trait)
.associated_type_by_name(&name![Output])
.expect("assoc ty value should not exist");
BuiltinImplAssocTyValueData {
impl_,
assoc_ty_id: output_ty_id,
num_vars: num_args as usize + 1,
value: output_ty,
}
}

View File

@ -12,15 +12,17 @@
};
use ra_db::{salsa::InternKey, CrateId};
use super::{builtin, AssocTyValue, ChalkContext, Impl};
use super::ChalkContext;
use crate::{
db::HirDatabase,
display::HirDisplay,
method_resolution::{TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS},
utils::generics,
CallableDef, DebruijnIndex, GenericPredicate, Substs, Ty, TypeCtor,
CallableDef, DebruijnIndex, FnSig, GenericPredicate, Substs, Ty, TypeCtor,
};
use mapping::{
convert_where_clauses, generic_predicate_to_inline_bound, make_binders, TypeAliasAsValue,
};
use mapping::{convert_where_clauses, generic_predicate_to_inline_bound, make_binders};
pub use self::interner::*;
@ -102,9 +104,9 @@ fn binder_kind(ty: &Ty, binders: &CanonicalVarKinds<Interner>) -> Option<chalk_i
let in_self = self.db.trait_impls_in_crate(self.krate);
let impl_maps = [in_deps, in_self];
let id_to_chalk = |id: hir_def::ImplId| Impl::ImplDef(id).to_chalk(self.db);
let id_to_chalk = |id: hir_def::ImplId| id.to_chalk(self.db);
let mut result: Vec<_> = if fps.is_empty() {
let result: Vec<_> = if fps.is_empty() {
debug!("Unrestricted search for {:?} impls...", trait_);
impl_maps
.iter()
@ -121,13 +123,6 @@ fn binder_kind(ty: &Ty, binders: &CanonicalVarKinds<Interner>) -> Option<chalk_i
.collect()
};
let arg: Option<Ty> =
parameters.get(1).map(|p| from_chalk(self.db, p.assert_ty_ref(&Interner).clone()));
builtin::get_builtin_impls(self.db, self.krate, &ty, &arg, trait_, |i| {
result.push(i.to_chalk(self.db))
});
debug!("impls_for_trait returned {} impls", result.len());
result
}
@ -217,32 +212,40 @@ fn closure_kind(
_closure_id: chalk_ir::ClosureId<Interner>,
_substs: &chalk_ir::Substitution<Interner>,
) -> rust_ir::ClosureKind {
// FIXME: implement closure support
unimplemented!()
// Fn is the closure kind that implements all three traits
rust_ir::ClosureKind::Fn
}
fn closure_inputs_and_output(
&self,
_closure_id: chalk_ir::ClosureId<Interner>,
_substs: &chalk_ir::Substitution<Interner>,
substs: &chalk_ir::Substitution<Interner>,
) -> chalk_ir::Binders<rust_ir::FnDefInputsAndOutputDatum<Interner>> {
// FIXME: implement closure support
unimplemented!()
let sig_ty: Ty =
from_chalk(self.db, substs.at(&Interner, 0).assert_ty_ref(&Interner).clone());
let sig = FnSig::from_fn_ptr_substs(
&sig_ty.substs().expect("first closure param should be fn ptr"),
false,
);
let io = rust_ir::FnDefInputsAndOutputDatum {
argument_types: sig.params().iter().map(|ty| ty.clone().to_chalk(self.db)).collect(),
return_type: sig.ret().clone().to_chalk(self.db),
};
make_binders(io.shifted_in(&Interner), 0)
}
fn closure_upvars(
&self,
_closure_id: chalk_ir::ClosureId<Interner>,
_substs: &chalk_ir::Substitution<Interner>,
) -> chalk_ir::Binders<chalk_ir::Ty<Interner>> {
// FIXME: implement closure support
unimplemented!()
let ty = Ty::unit().to_chalk(self.db);
make_binders(ty, 0)
}
fn closure_fn_substitution(
&self,
_closure_id: chalk_ir::ClosureId<Interner>,
_substs: &chalk_ir::Substitution<Interner>,
) -> chalk_ir::Substitution<Interner> {
// FIXME: implement closure support
unimplemented!()
Substs::empty().to_chalk(self.db)
}
fn trait_name(&self, _trait_id: chalk_ir::TraitId<Interner>) -> String {
@ -417,11 +420,8 @@ pub(crate) fn impl_datum_query(
) -> Arc<ImplDatum> {
let _p = ra_prof::profile("impl_datum");
debug!("impl_datum {:?}", impl_id);
let impl_: Impl = from_chalk(db, impl_id);
match impl_ {
Impl::ImplDef(impl_def) => impl_def_datum(db, krate, impl_id, impl_def),
_ => Arc::new(builtin::impl_datum(db, krate, impl_).to_chalk(db)),
}
let impl_: hir_def::ImplId = from_chalk(db, impl_id);
impl_def_datum(db, krate, impl_id, impl_)
}
fn impl_def_datum(
@ -472,7 +472,7 @@ fn impl_def_datum(
let name = &db.type_alias_data(type_alias).name;
trait_data.associated_type_by_name(name).is_some()
})
.map(|type_alias| AssocTyValue::TypeAlias(type_alias).to_chalk(db))
.map(|type_alias| TypeAliasAsValue(type_alias).to_chalk(db))
.collect();
debug!("impl_datum: {:?}", impl_datum_bound);
let impl_datum = ImplDatum {
@ -489,13 +489,8 @@ pub(crate) fn associated_ty_value_query(
krate: CrateId,
id: AssociatedTyValueId,
) -> Arc<AssociatedTyValue> {
let data: AssocTyValue = from_chalk(db, id);
match data {
AssocTyValue::TypeAlias(type_alias) => {
type_alias_associated_ty_value(db, krate, type_alias)
}
_ => Arc::new(builtin::associated_ty_value(db, krate, data).to_chalk(db)),
}
let type_alias: TypeAliasAsValue = from_chalk(db, id);
type_alias_associated_ty_value(db, krate, type_alias.0)
}
fn type_alias_associated_ty_value(
@ -518,7 +513,7 @@ fn type_alias_associated_ty_value(
let ty = db.ty(type_alias.into());
let value_bound = rust_ir::AssociatedTyValueBound { ty: ty.value.to_chalk(db) };
let value = rust_ir::AssociatedTyValue {
impl_id: Impl::ImplDef(impl_id).to_chalk(db),
impl_id: impl_id.to_chalk(db),
associated_ty_id: assoc_ty.to_chalk(db),
value: make_binders(value_bound, ty.num_binders),
};
@ -557,18 +552,6 @@ pub(crate) fn fn_def_datum_query(
Arc::new(datum)
}
impl From<AdtId> for crate::TypeCtorId {
fn from(struct_id: AdtId) -> Self {
struct_id.0
}
}
impl From<crate::TypeCtorId> for AdtId {
fn from(type_ctor_id: crate::TypeCtorId) -> Self {
chalk_ir::AdtId(type_ctor_id)
}
}
impl From<FnDefId> for crate::CallableDefId {
fn from(fn_def_id: FnDefId) -> Self {
InternKey::from_intern_id(fn_def_id.0)
@ -581,18 +564,6 @@ fn from(callable_def_id: crate::CallableDefId) -> Self {
}
}
impl From<ImplId> for crate::traits::GlobalImplId {
fn from(impl_id: ImplId) -> Self {
InternKey::from_intern_id(impl_id.0)
}
}
impl From<crate::traits::GlobalImplId> for ImplId {
fn from(impl_id: crate::traits::GlobalImplId) -> Self {
chalk_ir::ImplId(impl_id.as_intern_id())
}
}
impl From<OpaqueTyId> for crate::db::InternedOpaqueTyId {
fn from(id: OpaqueTyId) -> Self {
InternKey::from_intern_id(id.0)
@ -605,14 +576,14 @@ fn from(id: crate::db::InternedOpaqueTyId) -> Self {
}
}
impl From<rust_ir::AssociatedTyValueId<Interner>> for crate::traits::AssocTyValueId {
fn from(id: rust_ir::AssociatedTyValueId<Interner>) -> Self {
impl From<chalk_ir::ClosureId<Interner>> for crate::db::ClosureId {
fn from(id: chalk_ir::ClosureId<Interner>) -> Self {
Self::from_intern_id(id.0)
}
}
impl From<crate::traits::AssocTyValueId> for rust_ir::AssociatedTyValueId<Interner> {
fn from(assoc_ty_value_id: crate::traits::AssocTyValueId) -> Self {
rust_ir::AssociatedTyValueId(assoc_ty_value_id.as_intern_id())
impl From<crate::db::ClosureId> for chalk_ir::ClosureId<Interner> {
fn from(id: crate::db::ClosureId) -> Self {
chalk_ir::ClosureId(id.as_intern_id())
}
}

View File

@ -41,7 +41,7 @@ impl chalk_ir::interner::Interner for Interner {
type InternedCanonicalVarKinds = Vec<chalk_ir::CanonicalVarKind<Self>>;
type InternedConstraints = Vec<chalk_ir::InEnvironment<chalk_ir::Constraint<Self>>>;
type DefId = InternId;
type InternedAdtId = crate::TypeCtorId;
type InternedAdtId = hir_def::AdtId;
type Identifier = TypeAliasId;
type FnAbi = ();
@ -364,6 +364,18 @@ fn constraints_data<'a>(
) -> &'a [chalk_ir::InEnvironment<chalk_ir::Constraint<Self>>] {
constraints
}
fn debug_closure_id(
_fn_def_id: chalk_ir::ClosureId<Self>,
_fmt: &mut fmt::Formatter<'_>,
) -> Option<fmt::Result> {
None
}
fn debug_constraints(
_clauses: &chalk_ir::Constraints<Self>,
_fmt: &mut fmt::Formatter<'_>,
) -> Option<fmt::Result> {
None
}
}
impl chalk_ir::interner::HasInterner for Interner {

View File

@ -15,7 +15,7 @@
use crate::{
db::HirDatabase,
primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness},
traits::{builtin, AssocTyValue, Canonical, Impl, Obligation},
traits::{Canonical, Obligation},
ApplicationTy, CallableDef, GenericPredicate, InEnvironment, OpaqueTy, OpaqueTyId,
ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TyKind, TypeCtor,
};
@ -311,18 +311,24 @@ fn to_chalk(self, db: &dyn HirDatabase) -> TypeName<Interner> {
}
TypeCtor::Never => TypeName::Never,
// FIXME convert these
TypeCtor::Adt(_) | TypeCtor::FnPtr { .. } | TypeCtor::Closure { .. } => {
// other TypeCtors get interned and turned into a chalk StructId
let struct_id = db.intern_type_ctor(self).into();
TypeName::Adt(struct_id)
TypeCtor::Closure { def, expr } => {
let closure_id = db.intern_closure((def, expr));
TypeName::Closure(closure_id.into())
}
TypeCtor::Adt(adt_id) => TypeName::Adt(chalk_ir::AdtId(adt_id)),
TypeCtor::FnPtr { .. } => {
// This should not be reached, since Chalk doesn't represent
// function pointers with TypeName
unreachable!()
}
}
}
fn from_chalk(db: &dyn HirDatabase, type_name: TypeName<Interner>) -> TypeCtor {
match type_name {
TypeName::Adt(struct_id) => db.lookup_intern_type_ctor(struct_id.into()),
TypeName::Adt(struct_id) => TypeCtor::Adt(struct_id.0),
TypeName::AssociatedType(type_id) => TypeCtor::AssociatedType(from_chalk(db, type_id)),
TypeName::OpaqueType(opaque_type_id) => {
TypeCtor::OpaqueType(from_chalk(db, opaque_type_id))
@ -355,13 +361,16 @@ fn from_chalk(db: &dyn HirDatabase, type_name: TypeName<Interner>) -> TypeCtor {
let callable_def = from_chalk(db, fn_def_id);
TypeCtor::FnDef(callable_def)
}
TypeName::Array => TypeCtor::Array,
TypeName::Array | TypeName::Error => {
// this should not be reached, since we don't represent TypeName::Error with TypeCtor
unreachable!()
TypeName::Closure(id) => {
let id: crate::db::ClosureId = id.into();
let (def, expr) = db.lookup_intern_closure(id);
TypeCtor::Closure { def, expr }
}
TypeName::Closure(_) => {
// FIXME: implement closure support
TypeName::Error => {
// this should not be reached, since we don't represent TypeName::Error with TypeCtor
unreachable!()
}
}
@ -433,15 +442,15 @@ fn from_chalk(_db: &dyn HirDatabase, chalk: Self::Chalk) -> Self {
}
}
impl ToChalk for Impl {
impl ToChalk for hir_def::ImplId {
type Chalk = ImplId;
fn to_chalk(self, db: &dyn HirDatabase) -> ImplId {
db.intern_chalk_impl(self).into()
fn to_chalk(self, _db: &dyn HirDatabase) -> ImplId {
chalk_ir::ImplId(self.as_intern_id())
}
fn from_chalk(db: &dyn HirDatabase, impl_id: ImplId) -> Impl {
db.lookup_intern_chalk_impl(impl_id.into())
fn from_chalk(_db: &dyn HirDatabase, impl_id: ImplId) -> hir_def::ImplId {
InternKey::from_intern_id(impl_id.0)
}
}
@ -469,15 +478,20 @@ fn from_chalk(_db: &dyn HirDatabase, type_alias_id: AssocTypeId) -> TypeAliasId
}
}
impl ToChalk for AssocTyValue {
pub struct TypeAliasAsValue(pub TypeAliasId);
impl ToChalk for TypeAliasAsValue {
type Chalk = AssociatedTyValueId;
fn to_chalk(self, db: &dyn HirDatabase) -> AssociatedTyValueId {
db.intern_assoc_ty_value(self).into()
fn to_chalk(self, _db: &dyn HirDatabase) -> AssociatedTyValueId {
rust_ir::AssociatedTyValueId(self.0.as_intern_id())
}
fn from_chalk(db: &dyn HirDatabase, assoc_ty_value_id: AssociatedTyValueId) -> AssocTyValue {
db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into())
fn from_chalk(
_db: &dyn HirDatabase,
assoc_ty_value_id: AssociatedTyValueId,
) -> TypeAliasAsValue {
TypeAliasAsValue(TypeAliasId::from_intern_id(assoc_ty_value_id.0))
}
}
@ -686,52 +700,6 @@ fn from_chalk(
}
}
impl ToChalk for builtin::BuiltinImplData {
type Chalk = ImplDatum;
fn to_chalk(self, db: &dyn HirDatabase) -> ImplDatum {
let impl_type = rust_ir::ImplType::External;
let where_clauses = self.where_clauses.into_iter().map(|w| w.to_chalk(db)).collect();
let impl_datum_bound =
rust_ir::ImplDatumBound { trait_ref: self.trait_ref.to_chalk(db), where_clauses };
let associated_ty_value_ids =
self.assoc_ty_values.into_iter().map(|v| v.to_chalk(db)).collect();
rust_ir::ImplDatum {
binders: make_binders(impl_datum_bound, self.num_vars),
impl_type,
polarity: rust_ir::Polarity::Positive,
associated_ty_value_ids,
}
}
fn from_chalk(_db: &dyn HirDatabase, _data: ImplDatum) -> Self {
unimplemented!()
}
}
impl ToChalk for builtin::BuiltinImplAssocTyValueData {
type Chalk = AssociatedTyValue;
fn to_chalk(self, db: &dyn HirDatabase) -> AssociatedTyValue {
let ty = self.value.to_chalk(db);
let value_bound = rust_ir::AssociatedTyValueBound { ty };
rust_ir::AssociatedTyValue {
associated_ty_id: self.assoc_ty_id.to_chalk(db),
impl_id: self.impl_.to_chalk(db),
value: make_binders(value_bound, self.num_vars),
}
}
fn from_chalk(
_db: &dyn HirDatabase,
_data: AssociatedTyValue,
) -> builtin::BuiltinImplAssocTyValueData {
unimplemented!()
}
}
pub(super) fn make_binders<T>(value: T, num_vars: usize) -> chalk_ir::Binders<T>
where
T: HasInterner<Interner = Interner>,

View File

@ -279,10 +279,7 @@ macro_rules! sweep_each_query {
hir::db::InternImplQuery
// HirDatabase
hir::db::InternTypeCtorQuery
hir::db::InternTypeParamIdQuery
hir::db::InternChalkImplQuery
hir::db::InternAssocTyValueQuery
];
acc.sort_by_key(|it| std::cmp::Reverse(it.1));