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 @@ pub use hir_ty::db::{
AssociatedTyDataQuery, AssociatedTyValueQuery, CallableItemSignatureQuery, FieldTypesQuery, AssociatedTyDataQuery, AssociatedTyValueQuery, CallableItemSignatureQuery, FieldTypesQuery,
GenericDefaultsQuery, GenericPredicatesForParamQuery, GenericPredicatesQuery, HirDatabase, GenericDefaultsQuery, GenericPredicatesForParamQuery, GenericPredicatesQuery, HirDatabase,
HirDatabaseStorage, ImplDatumQuery, ImplSelfTyQuery, ImplTraitQuery, InferQueryQuery, HirDatabaseStorage, ImplDatumQuery, ImplSelfTyQuery, ImplTraitQuery, InferQueryQuery,
InherentImplsInCrateQuery, InternAssocTyValueQuery, InternChalkImplQuery, InternTypeCtorQuery, InherentImplsInCrateQuery, InternTypeParamIdQuery, ReturnTypeImplTraitsQuery, StructDatumQuery,
InternTypeParamIdQuery, ReturnTypeImplTraitsQuery, StructDatumQuery, TraitDatumQuery, TraitDatumQuery, TraitImplsInCrateQuery, TraitImplsInDepsQuery, TraitSolveQuery, TyQuery,
TraitImplsInCrateQuery, TraitImplsInDepsQuery, TraitSolveQuery, TyQuery, ValueTyQuery, ValueTyQuery,
}; };
#[test] #[test]

View file

@ -159,17 +159,17 @@ pub struct FunctionId(salsa::InternId);
type FunctionLoc = AssocItemLoc<Function>; type FunctionLoc = AssocItemLoc<Function>;
impl_intern!(FunctionId, FunctionLoc, intern_function, lookup_intern_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); pub struct StructId(salsa::InternId);
type StructLoc = ItemLoc<Struct>; type StructLoc = ItemLoc<Struct>;
impl_intern!(StructId, StructLoc, intern_struct, lookup_intern_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 struct UnionId(salsa::InternId);
pub type UnionLoc = ItemLoc<Union>; pub type UnionLoc = ItemLoc<Union>;
impl_intern!(UnionId, UnionLoc, intern_union, lookup_intern_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 struct EnumId(salsa::InternId);
pub type EnumLoc = ItemLoc<Enum>; pub type EnumLoc = ItemLoc<Enum>;
impl_intern!(EnumId, EnumLoc, intern_enum, lookup_intern_enum); impl_intern!(EnumId, EnumLoc, intern_enum, lookup_intern_enum);
@ -239,7 +239,7 @@ pub enum AssocContainerId {
impl_from!(ContainerId for AssocContainerId); impl_from!(ContainerId for AssocContainerId);
/// A Data Type /// A Data Type
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum AdtId { pub enum AdtId {
StructId(StructId), StructId(StructId),
UnionId(UnionId), UnionId(UnionId),

View file

@ -3,8 +3,8 @@
use std::sync::Arc; use std::sync::Arc;
use hir_def::{ use hir_def::{
db::DefDatabase, DefWithBodyId, FunctionId, GenericDefId, ImplId, LocalFieldId, TypeParamId, db::DefDatabase, expr::ExprId, DefWithBodyId, FunctionId, GenericDefId, ImplId, LocalFieldId,
VariantId, TypeParamId, VariantId,
}; };
use ra_arena::map::ArenaMap; use ra_arena::map::ArenaMap;
use ra_db::{impl_intern_key, salsa, CrateId, Upcast}; use ra_db::{impl_intern_key, salsa, CrateId, Upcast};
@ -12,9 +12,9 @@ use ra_prof::profile;
use crate::{ use crate::{
method_resolution::{InherentImpls, TraitImpls}, method_resolution::{InherentImpls, TraitImpls},
traits::{chalk, AssocTyValue, Impl}, traits::chalk,
Binders, CallableDef, GenericPredicate, InferenceResult, OpaqueTyId, PolyFnSig, Binders, CallableDef, GenericPredicate, InferenceResult, OpaqueTyId, PolyFnSig,
ReturnTypeImplTraits, TraitRef, Ty, TyDefId, TypeCtor, ValueTyDefId, ReturnTypeImplTraits, TraitRef, Ty, TyDefId, ValueTyDefId,
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
@ -77,17 +77,13 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
// Interned IDs for Chalk integration // Interned IDs for Chalk integration
#[salsa::interned] #[salsa::interned]
fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::TypeCtorId;
#[salsa::interned]
fn intern_callable_def(&self, callable_def: CallableDef) -> crate::CallableDefId; fn intern_callable_def(&self, callable_def: CallableDef) -> crate::CallableDefId;
#[salsa::interned] #[salsa::interned]
fn intern_type_param_id(&self, param_id: TypeParamId) -> GlobalTypeParamId; fn intern_type_param_id(&self, param_id: TypeParamId) -> GlobalTypeParamId;
#[salsa::interned] #[salsa::interned]
fn intern_impl_trait_id(&self, id: OpaqueTyId) -> InternedOpaqueTyId; fn intern_impl_trait_id(&self, id: OpaqueTyId) -> InternedOpaqueTyId;
#[salsa::interned] #[salsa::interned]
fn intern_chalk_impl(&self, impl_: Impl) -> crate::traits::GlobalImplId; fn intern_closure(&self, id: (DefWithBodyId, ExprId)) -> ClosureId;
#[salsa::interned]
fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> crate::traits::AssocTyValueId;
#[salsa::invoke(chalk::associated_ty_data_query)] #[salsa::invoke(chalk::associated_ty_data_query)]
fn associated_ty_data(&self, id: chalk::AssocTypeId) -> Arc<chalk::AssociatedTyDatum>; fn associated_ty_data(&self, id: chalk::AssocTypeId) -> Arc<chalk::AssociatedTyDatum>;
@ -151,3 +147,7 @@ impl_intern_key!(GlobalTypeParamId);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InternedOpaqueTyId(salsa::InternId); pub struct InternedOpaqueTyId(salsa::InternId);
impl_intern_key!(InternedOpaqueTyId); 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 } /// fn foo() -> i32 { 1 }
/// let bar: fn() -> i32 = foo; /// let bar: fn() -> i32 = foo;
/// ``` /// ```
// FIXME make this a Ty variant like in Chalk
FnPtr { num_args: u16, is_varargs: bool }, FnPtr { num_args: u16, is_varargs: bool },
/// The never type `!`. /// The never type `!`.
@ -139,13 +140,6 @@ pub enum TypeCtor {
Closure { def: DefWithBodyId, expr: ExprId }, 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 /// This exists just for Chalk, because Chalk just has a single `FnDefId` where
/// we have different IDs for struct and enum variant constructors. /// we have different IDs for struct and enum variant constructors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)] #[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_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
use tracing_tree::HierarchicalLayer; use tracing_tree::HierarchicalLayer;
let filter = EnvFilter::from_env("CHALK_DEBUG"); 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); let subscriber = Registry::default().with(filter).with(layer);
tracing::subscriber::set_default(subscriber) tracing::subscriber::set_default(subscriber)
} }

View file

@ -3,10 +3,8 @@ use std::sync::Arc;
use chalk_ir::cast::Cast; use chalk_ir::cast::Cast;
use chalk_solve::Solver; use chalk_solve::Solver;
use hir_def::{ use hir_def::{lang_item::LangItemTarget, TraitId};
expr::ExprId, lang_item::LangItemTarget, DefWithBodyId, ImplId, TraitId, TypeAliasId, use ra_db::CrateId;
};
use ra_db::{impl_intern_key, salsa, CrateId};
use ra_prof::profile; use ra_prof::profile;
use crate::{db::HirDatabase, DebruijnIndex, Substs}; use crate::{db::HirDatabase, DebruijnIndex, Substs};
@ -16,7 +14,6 @@ use super::{Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty,
use self::chalk::{from_chalk, Interner, ToChalk}; use self::chalk::{from_chalk, Interner, ToChalk};
pub(crate) mod chalk; pub(crate) mod chalk;
mod builtin;
// This controls the maximum size of types Chalk considers. If we set this too // 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 // high, we can run into slow edge cases; if we set it too low, Chalk won't
@ -274,47 +271,3 @@ impl FnTrait {
} }
} }
} }
#[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 hir_def::{
}; };
use ra_db::{salsa::InternKey, CrateId}; use ra_db::{salsa::InternKey, CrateId};
use super::{builtin, AssocTyValue, ChalkContext, Impl}; use super::ChalkContext;
use crate::{ use crate::{
db::HirDatabase, db::HirDatabase,
display::HirDisplay, display::HirDisplay,
method_resolution::{TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS}, method_resolution::{TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS},
utils::generics, 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::*; pub use self::interner::*;
@ -102,9 +104,9 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
let in_self = self.db.trait_impls_in_crate(self.krate); let in_self = self.db.trait_impls_in_crate(self.krate);
let impl_maps = [in_deps, in_self]; 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_); debug!("Unrestricted search for {:?} impls...", trait_);
impl_maps impl_maps
.iter() .iter()
@ -121,13 +123,6 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
.collect() .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()); debug!("impls_for_trait returned {} impls", result.len());
result result
} }
@ -217,32 +212,40 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
_closure_id: chalk_ir::ClosureId<Interner>, _closure_id: chalk_ir::ClosureId<Interner>,
_substs: &chalk_ir::Substitution<Interner>, _substs: &chalk_ir::Substitution<Interner>,
) -> rust_ir::ClosureKind { ) -> rust_ir::ClosureKind {
// FIXME: implement closure support // Fn is the closure kind that implements all three traits
unimplemented!() rust_ir::ClosureKind::Fn
} }
fn closure_inputs_and_output( fn closure_inputs_and_output(
&self, &self,
_closure_id: chalk_ir::ClosureId<Interner>, _closure_id: chalk_ir::ClosureId<Interner>,
_substs: &chalk_ir::Substitution<Interner>, substs: &chalk_ir::Substitution<Interner>,
) -> chalk_ir::Binders<rust_ir::FnDefInputsAndOutputDatum<Interner>> { ) -> chalk_ir::Binders<rust_ir::FnDefInputsAndOutputDatum<Interner>> {
// FIXME: implement closure support let sig_ty: Ty =
unimplemented!() 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( fn closure_upvars(
&self, &self,
_closure_id: chalk_ir::ClosureId<Interner>, _closure_id: chalk_ir::ClosureId<Interner>,
_substs: &chalk_ir::Substitution<Interner>, _substs: &chalk_ir::Substitution<Interner>,
) -> chalk_ir::Binders<chalk_ir::Ty<Interner>> { ) -> chalk_ir::Binders<chalk_ir::Ty<Interner>> {
// FIXME: implement closure support let ty = Ty::unit().to_chalk(self.db);
unimplemented!() make_binders(ty, 0)
} }
fn closure_fn_substitution( fn closure_fn_substitution(
&self, &self,
_closure_id: chalk_ir::ClosureId<Interner>, _closure_id: chalk_ir::ClosureId<Interner>,
_substs: &chalk_ir::Substitution<Interner>, _substs: &chalk_ir::Substitution<Interner>,
) -> chalk_ir::Substitution<Interner> { ) -> chalk_ir::Substitution<Interner> {
// FIXME: implement closure support Substs::empty().to_chalk(self.db)
unimplemented!()
} }
fn trait_name(&self, _trait_id: chalk_ir::TraitId<Interner>) -> String { fn trait_name(&self, _trait_id: chalk_ir::TraitId<Interner>) -> String {
@ -417,11 +420,8 @@ pub(crate) fn impl_datum_query(
) -> Arc<ImplDatum> { ) -> Arc<ImplDatum> {
let _p = ra_prof::profile("impl_datum"); let _p = ra_prof::profile("impl_datum");
debug!("impl_datum {:?}", impl_id); debug!("impl_datum {:?}", impl_id);
let impl_: Impl = from_chalk(db, impl_id); let impl_: hir_def::ImplId = from_chalk(db, impl_id);
match impl_ { impl_def_datum(db, krate, impl_id, 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)),
}
} }
fn impl_def_datum( fn impl_def_datum(
@ -472,7 +472,7 @@ fn impl_def_datum(
let name = &db.type_alias_data(type_alias).name; let name = &db.type_alias_data(type_alias).name;
trait_data.associated_type_by_name(name).is_some() 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(); .collect();
debug!("impl_datum: {:?}", impl_datum_bound); debug!("impl_datum: {:?}", impl_datum_bound);
let impl_datum = ImplDatum { let impl_datum = ImplDatum {
@ -489,13 +489,8 @@ pub(crate) fn associated_ty_value_query(
krate: CrateId, krate: CrateId,
id: AssociatedTyValueId, id: AssociatedTyValueId,
) -> Arc<AssociatedTyValue> { ) -> Arc<AssociatedTyValue> {
let data: AssocTyValue = from_chalk(db, id); let type_alias: TypeAliasAsValue = from_chalk(db, id);
match data { type_alias_associated_ty_value(db, krate, type_alias.0)
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)),
}
} }
fn type_alias_associated_ty_value( fn type_alias_associated_ty_value(
@ -518,7 +513,7 @@ fn type_alias_associated_ty_value(
let ty = db.ty(type_alias.into()); let ty = db.ty(type_alias.into());
let value_bound = rust_ir::AssociatedTyValueBound { ty: ty.value.to_chalk(db) }; let value_bound = rust_ir::AssociatedTyValueBound { ty: ty.value.to_chalk(db) };
let value = rust_ir::AssociatedTyValue { 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), associated_ty_id: assoc_ty.to_chalk(db),
value: make_binders(value_bound, ty.num_binders), value: make_binders(value_bound, ty.num_binders),
}; };
@ -557,18 +552,6 @@ pub(crate) fn fn_def_datum_query(
Arc::new(datum) 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 { impl From<FnDefId> for crate::CallableDefId {
fn from(fn_def_id: FnDefId) -> Self { fn from(fn_def_id: FnDefId) -> Self {
InternKey::from_intern_id(fn_def_id.0) InternKey::from_intern_id(fn_def_id.0)
@ -581,18 +564,6 @@ impl From<crate::CallableDefId> for FnDefId {
} }
} }
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 { impl From<OpaqueTyId> for crate::db::InternedOpaqueTyId {
fn from(id: OpaqueTyId) -> Self { fn from(id: OpaqueTyId) -> Self {
InternKey::from_intern_id(id.0) InternKey::from_intern_id(id.0)
@ -605,14 +576,14 @@ impl From<crate::db::InternedOpaqueTyId> for OpaqueTyId {
} }
} }
impl From<rust_ir::AssociatedTyValueId<Interner>> for crate::traits::AssocTyValueId { impl From<chalk_ir::ClosureId<Interner>> for crate::db::ClosureId {
fn from(id: rust_ir::AssociatedTyValueId<Interner>) -> Self { fn from(id: chalk_ir::ClosureId<Interner>) -> Self {
Self::from_intern_id(id.0) Self::from_intern_id(id.0)
} }
} }
impl From<crate::traits::AssocTyValueId> for rust_ir::AssociatedTyValueId<Interner> { impl From<crate::db::ClosureId> for chalk_ir::ClosureId<Interner> {
fn from(assoc_ty_value_id: crate::traits::AssocTyValueId) -> Self { fn from(id: crate::db::ClosureId) -> Self {
rust_ir::AssociatedTyValueId(assoc_ty_value_id.as_intern_id()) 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 InternedCanonicalVarKinds = Vec<chalk_ir::CanonicalVarKind<Self>>;
type InternedConstraints = Vec<chalk_ir::InEnvironment<chalk_ir::Constraint<Self>>>; type InternedConstraints = Vec<chalk_ir::InEnvironment<chalk_ir::Constraint<Self>>>;
type DefId = InternId; type DefId = InternId;
type InternedAdtId = crate::TypeCtorId; type InternedAdtId = hir_def::AdtId;
type Identifier = TypeAliasId; type Identifier = TypeAliasId;
type FnAbi = (); type FnAbi = ();
@ -364,6 +364,18 @@ impl chalk_ir::interner::Interner for Interner {
) -> &'a [chalk_ir::InEnvironment<chalk_ir::Constraint<Self>>] { ) -> &'a [chalk_ir::InEnvironment<chalk_ir::Constraint<Self>>] {
constraints 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 { impl chalk_ir::interner::HasInterner for Interner {

View file

@ -15,7 +15,7 @@ use ra_db::salsa::InternKey;
use crate::{ use crate::{
db::HirDatabase, db::HirDatabase,
primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness}, primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness},
traits::{builtin, AssocTyValue, Canonical, Impl, Obligation}, traits::{Canonical, Obligation},
ApplicationTy, CallableDef, GenericPredicate, InEnvironment, OpaqueTy, OpaqueTyId, ApplicationTy, CallableDef, GenericPredicate, InEnvironment, OpaqueTy, OpaqueTyId,
ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TyKind, TypeCtor, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TyKind, TypeCtor,
}; };
@ -311,18 +311,24 @@ impl ToChalk for TypeCtor {
} }
TypeCtor::Never => TypeName::Never, TypeCtor::Never => TypeName::Never,
// FIXME convert these TypeCtor::Closure { def, expr } => {
TypeCtor::Adt(_) | TypeCtor::FnPtr { .. } | TypeCtor::Closure { .. } => { let closure_id = db.intern_closure((def, expr));
// other TypeCtors get interned and turned into a chalk StructId TypeName::Closure(closure_id.into())
let struct_id = db.intern_type_ctor(self).into(); }
TypeName::Adt(struct_id)
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 { fn from_chalk(db: &dyn HirDatabase, type_name: TypeName<Interner>) -> TypeCtor {
match type_name { 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::AssociatedType(type_id) => TypeCtor::AssociatedType(from_chalk(db, type_id)),
TypeName::OpaqueType(opaque_type_id) => { TypeName::OpaqueType(opaque_type_id) => {
TypeCtor::OpaqueType(from_chalk(db, opaque_type_id)) TypeCtor::OpaqueType(from_chalk(db, opaque_type_id))
@ -355,13 +361,16 @@ impl ToChalk for TypeCtor {
let callable_def = from_chalk(db, fn_def_id); let callable_def = from_chalk(db, fn_def_id);
TypeCtor::FnDef(callable_def) TypeCtor::FnDef(callable_def)
} }
TypeName::Array => TypeCtor::Array,
TypeName::Array | TypeName::Error => { TypeName::Closure(id) => {
// this should not be reached, since we don't represent TypeName::Error with TypeCtor let id: crate::db::ClosureId = id.into();
unreachable!() 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!() unreachable!()
} }
} }
@ -433,15 +442,15 @@ impl ToChalk for Mutability {
} }
} }
impl ToChalk for Impl { impl ToChalk for hir_def::ImplId {
type Chalk = ImplId; type Chalk = ImplId;
fn to_chalk(self, db: &dyn HirDatabase) -> ImplId { fn to_chalk(self, _db: &dyn HirDatabase) -> ImplId {
db.intern_chalk_impl(self).into() chalk_ir::ImplId(self.as_intern_id())
} }
fn from_chalk(db: &dyn HirDatabase, impl_id: ImplId) -> Impl { fn from_chalk(_db: &dyn HirDatabase, impl_id: ImplId) -> hir_def::ImplId {
db.lookup_intern_chalk_impl(impl_id.into()) InternKey::from_intern_id(impl_id.0)
} }
} }
@ -469,15 +478,20 @@ impl ToChalk for TypeAliasId {
} }
} }
impl ToChalk for AssocTyValue { pub struct TypeAliasAsValue(pub TypeAliasId);
impl ToChalk for TypeAliasAsValue {
type Chalk = AssociatedTyValueId; type Chalk = AssociatedTyValueId;
fn to_chalk(self, db: &dyn HirDatabase) -> AssociatedTyValueId { fn to_chalk(self, _db: &dyn HirDatabase) -> AssociatedTyValueId {
db.intern_assoc_ty_value(self).into() rust_ir::AssociatedTyValueId(self.0.as_intern_id())
} }
fn from_chalk(db: &dyn HirDatabase, assoc_ty_value_id: AssociatedTyValueId) -> AssocTyValue { fn from_chalk(
db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into()) _db: &dyn HirDatabase,
assoc_ty_value_id: AssociatedTyValueId,
) -> TypeAliasAsValue {
TypeAliasAsValue(TypeAliasId::from_intern_id(assoc_ty_value_id.0))
} }
} }
@ -686,52 +700,6 @@ where
} }
} }
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> pub(super) fn make_binders<T>(value: T, num_vars: usize) -> chalk_ir::Binders<T>
where where
T: HasInterner<Interner = Interner>, T: HasInterner<Interner = Interner>,

View file

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